[英]rspec controller test not working when trying to test for scope
I have a controller method like so:我有一个像这样的控制器方法:
def count
response = model.scope(params[:age])
render json: {count: response.count}
end
Where the scope is supposed to query the table for the model with any records that have records with the specified age.范围应该在表中查询具有指定年龄记录的任何记录的模型。 The controller method works fine but writing the rspec test for it is not working.
控制器方法工作正常,但为其编写 rspec 测试不起作用。
I try to make some test data for the model like so:我尝试为模型制作一些测试数据,如下所示:
let(:model) {create(:model, age:20) }
and then in my rspec test I try something like然后在我的 rspec 测试中我尝试类似
it "calls endpoint and returns correct count" do
get :method, params: {age:20}
puts parsed_response
end
I would assume that this test makes a get request to my endpoint with 20 as the age parameter.我假设这个测试以 20 作为年龄参数向我的端点发出 get 请求。 Since I made fake data for the model with one instance having age 20, I would assume the count would return 1 for the test.
由于我为模型制作了一个年龄为 20 岁的假数据,因此我假设计数将返回 1 进行测试。 However it returns 0 when I view the parsed response in the puts.
但是,当我在 puts 中查看解析的响应时,它返回 0。 Is my undertsanding of how factory bot works incorrect?
我对工厂机器人如何工作的理解不正确吗? Am I testing the count incorrectly?
我是否错误地测试了计数?
Try changing from尝试从
let(:model) {create(:model, age:20) }
to至
let!(:model) {create(:model, age:20) }
let
and let!
let
和let!
here Usually I avoid using let!.通常我避免使用 let!。 Try changing your test case to
尝试将您的测试用例更改为
it "calls endpoint and returns correct count" do
create(:model, age:20)
get :method, params: {age:20}
puts parsed_response
end
Also, pro tip about debugging另外,关于调试的专业提示
def count
p model.all <<<----- add this line to see what all records you have?
response = model.scope(params[:age])
render json: {count: response.count}
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.