36

I'm trying to test if an array includes another (rspec 2.11.0)

test_arr = [1, 3]

describe [1, 3, 7] do
  it { should include(1,3) }
  it { should eval("include(#{test_arr.join(',')})")}
  #failing
  it { should include(test_arr) }
end    

this is the result rspec spec/test.spec ..F

Failures:

  1) 1 3 7 
     Failure/Error: it { should include(test_arr) }
       expected [1, 3, 7] to include [1, 3]
     # ./spec/test.spec:7:in `block (2 levels) in <top (required)>'

Finished in 0.00125 seconds
3 examples, 1 failure

Failed examples:

rspec ./spec/test.spec:7 # 1 3 7 

The include rspec mehod no accepts an array argument, theres a better way to avoid "eval"?

2 Answers 2

65

Just use the splat (*) operator, which expands an array of elements into a list of arguments which can be passed to a method:

test_arr = [1, 3]

describe [1, 3, 7] do
  it { should include(*test_arr) }
end
2
  • 4
    OMG! This is mind-blowing...serious, this is really really useful in specs, I didn't know #include supported list of arguments. Thank you! Jun 18, 2014 at 17:18
  • TIL about the splat operator.. and that it's not even required if the array is defined inline, in my case I did it { should include(1, 3) } (edit: which is exactly what the splat operator does.. )
    – Alex Wally
    Dec 22, 2022 at 22:56
7

If you'd like to assert the order of the subset array, you'll need to do a bit more than should include(..), because RSpec's include matcher only asserts that each element shows up anywhere in the array, not that all the arguments show up in order.

I ended up using each_cons to verify that the sub-array is present in order, like this:

describe [1, 3, 5, 7] do
  it 'includes [3,5] in order' do
    subject.each_cons(2).should include([3,5])
  end

  it 'does not include [3,1]' do
    subject.each_cons(2).should_not include([3,1])
  end
end
1
  • Honestly this is brilliant. Lets me check exactly what I need. Mar 19, 2021 at 10:28

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.