2

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

4

1 回答 1

2

面对这些问题时,我倾向于将查询封装在一个方法中。这样一来,您就可以简单地用数据剔除该方法,而无需担心数据卫生问题。

例如:

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

此时,您可以在需要测试依赖于它的事物时将方法存根:

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

至于测试实际方法,我不确定你是否需要。该方法链中没有多少有趣的部分。如果您想完整,以下是案例:

  • 确保fetch_table1_results使用 id 调用 Table1.find 的任何实例
  • 确保fetch_table1_results急切加载table2table3

执行后者的方式各不相同,但我更喜欢直接检查数据库查询(这不会是一种流行的观点)。因此,您可以键入如下内容:

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

那个,或者类似的东西。我还应该注意,这些测试应该在模型中,而不是控制器中。

于 2013-07-10T21:54:56.940 回答