2

I have this code in my model.

belongs_to :user, -> { includes :user_profile }

I went through shoulda doc i did not found any way to test that proc containing includes part. Please help.

Sachin Singh
  • 7,107
  • 6
  • 40
  • 80

1 Answers1

0

Assuming the model in question is named Car (you haven't posted the name of the enclosing class so I'm totally making this up) you can test it as:

describe 'user' do
  let(:car) { create_car_somehow }

  it 'preloads the user_profile association' do
    expect(car.user.association(:user_profile)).to be_loaded
  end
end

#association returns metadata of the specified association (of type ActiveRecord::Associations::BelongsToAssociation and so on). The returned object responds to #loaded? which returns true if the association has been loaded and false otherwise.

Greg Navis
  • 2,818
  • 10
  • 10
  • 1
    where is `be_loaded` defined? Can you post a link to the docs? – Anthony Mar 02 '17 at 12:41
  • 1
    It's a dynamic [predicate matcher](https://www.relishapp.com/rspec/rspec-expectations/v/2-2/docs/matchers/predicate-matchers) defined on the fly. Basically, `expect(object).to be_foo` is automatically converted to `expect(object.foo?).to be_truthy`. – Greg Navis Mar 02 '17 at 13:10