简体   繁体   中英

Rspec test belongs_to with shoulda_matchers

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM