Arepo
Arepo

Reputation: 889

Shoulda-matchers throwing confusing errors

I'm having problems with what I think is the shoulda-matchers gem after updating it from v1.4.2 to v2.7.0, and the failures differ depending on how I run the tests. When I run the current test suite 'normally', I get failures like this:

Failure/Error: it {should validate_presence_of :attribute1}

Expected errors to include "can't be blank" when primary_first_name is set to nil, got errors: ["can't be blank (attribute: \"attribute2\", value: nil)", "can't be blank (attribute: \"attribute3\", value: nil)"]

While this was happening, I tried setting up Spring and then Zeus to speed up the tests (we're using pre-Spring Rails 3.2.18), both of which changed the error output. Errors of the form above disappeared, but this sort replaced it:

Failure/Error: it {should validate_presence_of :attribute}

NoMethodError: undefined method `validate_presence_of' for #RSpec::ExampleGroups::(Model instance)> (opening angle bracket deleted to make it appear here)

I also found a bunch of other tests started failing, with this sort of error:

Failure/Error: it {should have_db_column :column_name} expected #<(Model Instance> to respond to has_db_column?

I found a report discussing the latter problem, but it seemed to be a shoulda-matchers/Spring clash, so I don't know why Zeus should cause the same problem.

I don't know if the first problem is underlying or exacerbating the second. All three gems are new to me (I'm working on legacy code), so my fallback fix will be to just get rid of shoulda-matchers (which I updated as a response to another problem it seemed to be causing) and rewrite the tests that rely on it. Is there a less drastic option?

Upvotes: 2

Views: 373

Answers (1)

GMarx
GMarx

Reputation: 483

One part of it may be an error in your test setup (in the spec) & then how the model is built to pass the test. The Model should have a validates component, which responds to the test.

Let's take this part of your error:

Failure/Error: it {should validate_presence_of :attribute1}

Expected errors to include "can't be blank" when primary_first_name is set to nil, ...

that tells me you created a shoulda validation in the spec on the presence of attribute1, where you would then need to validate attribute1 in the model for presence

then you have the errors of what was received:

got errors: ["can't be blank (attribute: \"attribute2\", value: nil)", "can't be blank (attribute: \"attribute3\", value: nil)"]

multiple errors, for attributes being passed in in hashes, when it was expecting only 1 attribute.

without knowing what your spec & model look like, I can only hypothesize, but here is how I would write it:

spec:

it { is_expected_to validate_presence_of(:attribute1) }

Then, your model would have the validation which corresponds, to match it:

validates :attribute1, presence: true

Upvotes: 1

Related Questions