Rails testing / How to use assert_equal on arrays

The answer is simple: don't.
Instead use assert_same_elements from gem shoulda. Details below.

Imagine you have a test like this:

and a fixture file that looks like the following:

Then, depending on a test environment setup, you might get very different results, sometimes tests like that one will pass, sometimes not.

As you may see from the test results, the only difference is the order of array elements. As a consequence, the test failed due to the fact that arrays are compared preserving the order of their elements (even though arrays imply no persistent ordering).
One way to solve this issue is to use gem 'shoulda' (shoulda-context):


Why not just do assert_same_elements json_response, expected? Because at the moment of writing assert_same_elements is not doing recursive comparison.

No comments:

Post a Comment