Flip Flip - 7 months ago 19
Ruby Question

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

Answer

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