简体   繁体   English

如何为以下查询编写Rspec规范

[英]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 . 嗨,我在控制器中有以下查询,我想编写Rspec规范。 I am new to Rspec and I don't know how to write the spec. 我是Rspec的新手,我不知道如何编写规范。 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 谢谢

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 确保fetch_table1_results调用ID为ID的Table1.find的任何实例
  • Ensure fetch_table1_results eager-loads table2 and table3 确保fetch_table1_results加载table2table3

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. 我还要注意,这些测试应该在模型中,而不是控制器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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