3

One of my models' default scope is set to automatically load a related model with includes(). How can I test this functionality with RSpec? I tried running:

Model.includes(:relation).to_sql

Hoping I could detect the signature in the SQL, but it only returned this:

SELECT "models".* FROM "models"

No mention of the relation, it's apparently done with a second query. How would you recommend testin this?

Jonah
  • 9,991
  • 5
  • 45
  • 79
  • 2
    Refer to this [SO question](http://stackoverflow.com/questions/1376212/how-to-determine-if-rails-association-is-eager-loaded) – konyak Mar 30 '15 at 14:53

2 Answers2

1

I would probably go down the route of stubbing the method and setting an expectation.

The pattern would be to add a test double of your model and set the expectation that it receives the .includes method call

Testing the actual SQL call created by Rails seems to be more about testing Rails rather than your app and tightly couples it to the implementation. Testing that the method gets called is a good middle ground, with the knowledge that if it gets called, Rails will do the right thing.

There is a lot more information here https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/method-stubs to better understand the process.

Dhruvil Dave
  • 109
  • 1
  • 20
muttonlamb
  • 6,341
  • 3
  • 26
  • 35
  • 1
    I'm not sure how to apply that, can you give some example code on how to test that the `includes` method was called? I agree, testing the raw SQL would be a little too close to implementation to be practical. My intention was to compare it to the SQL generated by another query, restricting it to testing just the results. – Jonah Dec 02 '13 at 18:07
0

includes(:relation) will add a left outer join relations to your query. This means you can use relations in your query without having to joins(:relations).

let!(:model) {
  Model.create!( field: 42 )
}
let!(:relation) {
  model.relations.create!( this: "that")
}

it 'includes relation' do
  expect( Model.where("relations.this": "that") ).to contain_exactly(relation)
end
Schwern
  • 153,029
  • 25
  • 195
  • 336