10

I have a method which returns an array. I need to test it using rspec. Is there any method with which we can test like:

def get_ids
  ####returns array of ids
end

subject.get_ids.should be_array

or

result = subject.get_ids
result.should be an_instance_of(Array)
1
  • result.class.should eq Array Commented Oct 28, 2014 at 8:29

1 Answer 1

25

Well, depends on what exactly you're looking for.

To check if the returned value is an array (be_an_instance_of):

expect(subject.get_ids).to be_an_instance_of(Array)

or to check if the returned value matches the content of expected array (match_array):

expect(subject.get_ids).to match_array(expected_array)

Update:

As mentioned in Patrick's comment, to check equivalence match of array use eq:

expect(subject.get_ids).to eq(expected_array)

For identity match of array use equal:

expect(subject.get_ids).to equal(expected_array)
Sign up to request clarification or add additional context in comments.

7 Comments

eq will also work if you know the contents of the array. I think in this case it is best to do an exact match.
@p11y : Actually eq will do an exact match while match_array will check if contents of the source array matches exactly with the target array, i.e., expect([1, 2, 3]).to match_array([3, 2, 1]) will work while expect([1, 2, 3]).to eq([3, 2, 1]) won't. Or I misunderstood your point? Here, you may not know the order of ids you get from the method, so you might not want to do an exact array match, instead better to do an exact content match.
I just wanted to point out that I tend to prefer the most restrictive assertion possible. I generally start out with eq and only when I notice that I don't care about order, I switch to match_array. It is easy to form a habit using match_array and then miss cases where the order is important. Same principle applies to other kinds of assertions, for example I prefer eq('Hello, Zaphod!') above match(/Zaphod/). It's easier to understand and at the same time more specific. Of course there are exceptions to this, above all when you don't want your tests to break when other units change.
Ahh, I see. Completely agree with your point on forming this as a habit and then carrying it on in future. Sometimes an exact match is necessary to see if your code is producing the desired output. For example: You might not want to use match_array if you're testing a sorting/filtering functionality.
@GiovanniBenussi : You wouldn't know if it is a Hash or some other object responding to each due to duck typing.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.