gates
gates

Reputation: 4583

How do i check the valid association and the related model existence

I am following this pattern

it { is_expected.to respond_to(:cars) } for checking the association

Now accidentally in the model, let's assume I have this line

has_many :bars

So in the test, after seeing the model. I went ahead and did this

it { is_expected.to respond_to(:bars) }

And the test passes, but there is no model Bar how do we rectify this.

Upvotes: 1

Views: 86

Answers (2)

Greg
Greg

Reputation: 6628

has_many :bars adds many methods to your model, bars is one of them, and respond_to matcher just check if there's such publicly available method - so you don't really testing what you think you would like to test.

You could for example do something like this:

expect(subject.bars.build).to be_instance_of(Bar)

This spec would fail if Bar does not exist.

I'm also pretty sure that

expect(subject.bars).to eq []

Would fail too, since it should try to find those in the DB, and missing model would surface here as well.

Also this

expect{ subject.bars.build }.not_to raise_exception

should also fail.

That's generally the problem with dynamic languages - errors (including typos) are not immediately caught.

I actually didn't know that you can define a relation to unexisting model. But it makes sense - checking if the classes exists during the class definition could be a bit too heavy.

Upvotes: 1

Derek Prior
Derek Prior

Reputation: 3507

I have an answer in a few parts. First, you can help avoid these typos of errors by test-driving your implementation. If you write a failing test first, the error message is another opportunity for you to recognize the typo: "Wait, a minute... it doesn't make sense for this to respond to bars. That's not what I meant..."

The larger answer is that this test on its own has so little value as to be worthless. If you make the typo above in both the implementation and that test and no other test fails then it's hard for me to believe it matters at all if the object response to cars, bars or any other typo.

A more valuable test would exercise the behavior of the association. For instance, if you wanted to test that a Person could associate a Car to their user, you could start with a feature test that exercises that feature. The test failure would guide you toward a working implementation that may or may not require that association. But if you typo the association you will find out because you are testing actual behavior.

Upvotes: 0

Related Questions