Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Rspec spec for the following query

Hi I have the following query in my controller and I want to write the Rspec spec . I am new to Rspec and I don't know how to write the spec. Kindly help

table1.includes(:table2).where(table1: {id: params[:id]}).includes(:table3)

I also tried looking into mocks and stubs but i don't understand how to use them for a query like this.

Thanks

like image 485
rajkumarts Avatar asked Dec 07 '25 09:12

rajkumarts


1 Answers

When faced with these issues, I tend to encapsulate the query in a method. That way, you can stub out the method with data simply and without worrying about data-sanitation.

For example:

def fetch_table1_results(id)
  table1.includes(:table2).where(table1: {id: id}).includes(:table3)
end

At this point, you can stub out the method when you need to test things that depend on it:

awesome_model = stub_model(Table1, fetch_table1_results: [1, 2, 'etc']) # You should include models, stubs, or mocks here.

As far as testing the actual method, I'm not sure you need to. There aren't many interesting parts of that method chain. If you wanted to be complete, here are the cases:

  • Ensure fetch_table1_results calls any instance of Table1.find with id
  • Ensure fetch_table1_results eager-loads table2 and table3

The way of doing the latter varies, but I'm rather fond (and this won't be a popular opinion) of checking the database query directly. So you could type something like the following:

fetch_table1_results(1).to_sql.should include('JOIN table2')

That, or something similar. I should also note that these tests should be in the model, not the controller.

like image 85
Chuck Callebs Avatar answered Dec 10 '25 01:12

Chuck Callebs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!