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"?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With