Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I test associations between models?

Should I write a test for an association between two models?

I just found this code in one of my first Rails projects and this doesn't seem correct as not having the association causes an error rather than a failure. So how and where would I test them correctly?

require 'test_helper'

class VocabTest < ActiveSupport::TestCase

  test "Must have 'belongs_to user' association" do
    assert @vocab.user
  end
end
like image 967
Flip Avatar asked Apr 21 '16 13:04

Flip


2 Answers

No, you don't need to specifically unit-test associations, even if your goal is to completely test your application (which you should). Associations are only implementation; they exist to support behavior, and testing that behavior always fully tests the existence of the associations. Separate unit tests of the associations don't add any value.

If you're practicing test-driven development and in the middle of implementing some behavior that requires an association, you might find it helpful to write a unit test for the association, get that to pass, and return to finish the test of the behavior. I don't normally find I need this, since in Rails adding an association to existing models, or even adding a new model, is pretty simple, but some people like the support of intermediate tests. However, once the behavior was implemented I'd delete the test of the association, as I would any redundant test.

I wrote more on the usefulness of directly testing various aspects of ActiveRecord models in this answer and this answer.

like image 183
Dave Schweisguth Avatar answered Sep 25 '22 06:09

Dave Schweisguth


I tend to test associations between models to confirm that I have done all the setup correctly. A really easy way to test associations is with shoulda.

You would be able to make your test files more readable as well

require 'test_helper'

class VocabTest < ActiveSupport::TestCase

  test "associations" do
    should belong_to :user
  end

end
like image 37
margo Avatar answered Sep 24 '22 06:09

margo