Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How rspec array should include? another array

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"?

  • Source
  • Spec
like image 331
GioM Avatar asked Jan 08 '13 11:01

GioM


2 Answers

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
like image 143
Chris Salzberg Avatar answered Nov 18 '22 14:11

Chris Salzberg


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
like image 6
phinze Avatar answered Nov 18 '22 13:11

phinze