Should I test associations between models?

Should I write a test for communication between two models?

I just found this code in one of my first Rails projects, and this does not seem to be correct, since a lack of communication causes an error, not 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 
+5
source share
2 answers

I am trying to check the associations between the models to confirm that I have correctly completed all the settings. A very easy way to test associations is shoulda .

You can also make your test files more readable.

 require 'test_helper' class VocabTest < ActiveSupport::TestCase test "associations" do should belong_to :user end end 
+7
source

No, you do not need specific associations for testing modules, even if your goal is to fully test your application (what you need). Associations are only an implementation; they exist to support behavior, and testing this behavior always fully verifies the existence of associations. Separate unit unit tests of associations add no value.

If you practice test-based development and in the middle of implementing some kind of behavior that requires association, it might be helpful to write a unit test for the association, get it to pass, and come back to finish the behavior test. Usually I don’t find that I need it, because in Rails, adding a link to existing models or even adding a new model is quite simple, but some people like intermediate test support. However, once the behavior has been implemented, I will remove the association check, since I would use an extra test.

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

+3
source

Source: https://habr.com/ru/post/1247625/


All Articles