Dave
Dave

Reputation: 19110

How do I test belongs_to associations with Rails 6 and RSpec 4.1?

I’m upgrading from Rails 4.2 to 6. I'm also using FactoryBot 6.2.0. I have this model

class Book < ActiveRecord::Base
  belongs_to :author, inverse_of: :book
    …
  validates :model, presence: true, unless: -> { author.check_vwf? }

I have an RSpec (rspec-rails 4.1.2 ) test where I want to test an association …

describe Book do

    …
  it { should belong_to :author }

But running this test fails with the below error. It appears that the “validates” method is getting run and the instance being constructed has no “belongs_to” association, but that is exactly what I’m trying to test …

 Failure/Error: validates :model, presence: true, unless: -> { author.check_vwf? }
 
 NoMethodError:
   undefined method `check_vwf?' for nil:NilClass

Something about upgrading my Rails caused this test to suddenly fail. What’s the proper way with the given version of Rails and RSpec to test an association?

Upvotes: 5

Views: 1116

Answers (2)

Licke
Licke

Reputation: 191

I think your issues could be related to your association. Since Rails 5 the belongs_to association is required by default.

If you want to be able to create records without the association you need to add the following:

 belongs_to :author, inverse_of: :book, optional: true

Upvotes: 1

Shoulda matcher is defining a subject by default, but this subject creates a problem for your case. You could try adding the following at the start of the test file to override the default one.

let!(:author) { create(:author) }
subject { create(:book, author: author) }

Assuming you have defined the author and book factories.

Upvotes: 1

Related Questions