[英]how to write controller test in Rails
I'm really not sure how to write a controller test. 我真的不确定如何编写控制器测试。
Given is one of the controller action. 给定是控制器动作之一。
class AccountsController < ApplicationController
def pstn_rate_imports
page = params[:page] || 1
@pstn_rate_imports = @resporg_account_id.pstn_rate_imports.order('created_at desc').page(page).per(10)
@pstn_rate_import = PstnRateImport.new
end
end
Now I approach this in 2 way.. 现在,我以两种方式处理此问题。
Like, 喜欢,
get :pstn_rate_imports, id: 1, page: 1
expect(assigns(:pstn_rates_imports)).to eq(expected_result)
but here a problem, I would now need to sure of that I insert a correct data on DB (worry about validation etc, etc when creating records) Also, this does not adhere to the principle that any new chance you introduce should break your test. 但是这里有一个问题,我现在需要确保我在数据库上插入了正确的数据(担心在创建记录时会进行验证等问题)。此外,这并不符合您引入的任何新机会都会破坏测试的原则。
expect_any_instance_of(ResporgAccountId).to receive(:pstn_rate_imports) { some_arel }
Expect_any_instance_of(ResporgAccountId).to接收(:pstn_rate_imports){some_arel}
expect(some_arel).to receive(:order).with('created_at desc') { some_arel }
期望(some_arel)。接收(:order).with('created_at desc'){some_arel}
expect(some_arel).to receive(:page).with('1') { some_arel }
期望(some_arel)。接收(:page).with('1'){some_arel}
expect(some_arel).to receive(:per).with(10) { some_arel }
期望(some_arel)。接收(:per).with(10){some_arel}
get :pstn_rate_imports, id: 1, page: 1
得到:pstn_rate_imports,id:1,页面:1
This ensures that if I change anything the test would fail. 这样可以确保如果我进行任何更改,测试都将失败。 But the problem is that I'm not sure how to
mock the arel object or ActiveRecord method that returns an arel object
. 但是问题是我不确定如何
mock the arel object or ActiveRecord method that returns an arel object
。
So what is the correct way to write controller test in Rails. 那么在Rails中编写控制器测试的正确方法是什么。
The main principle is writing a test that covers the tested object functionality only. 主要原理是编写仅涵盖测试对象功能的测试。
So you need to: 因此,您需要:
pstn_rate_imports
method) creating a relative test for the model method pstn_rate_imports
方法),为模型方法创建相对测试 .order
) in the controller. .order
)。 Model's methods (like pstn_rate_imports
) should be stubbed for sure. pstn_rate_imports
)进行存根处理。 You can read more about the stubbing here .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.