[英]Stubbing named_scope in an RSpec Controller
对于像这样的情况,我找不到任何东西。 我有一个模型,它具有如此定义的命名范围:
class Customer < ActiveRecord::Base
# ...
named_scope :active_customers, :conditions => { :active => true }
end
我试图在我的Controller规范中将其删除:
# spec/customers_controller_spec.rb
describe CustomersController do
before(:each) do
Customer.stub_chain(:active_customers).and_return(@customers = mock([Customer]))
end
it "should retrieve a list of all customers" do
get :index
response.should be_success
Customer.should_receive(:active_customers).and_return(@customers)
end
end
这不起作用并且失败,说客户期望active_customers但是收到它0次。 在我的实际控制器中,我有@customers = Customer.active_customers
。 为了让这个工作,我错过了什么? 可悲的是,我发现编写代码比编写测试/规范更容易,并且写了因为我知道规范描述的内容,而不是如何告诉RSpec我想做什么。
我认为在存根和消息期望方面存在一些混淆。 消息期望基本上是存根,您可以在其中设置所需的预设响应,但它们还会测试要测试的代码进行的调用。 相比之下,存根只是方法调用的固定响应。 但是不要在相同的方法和测试中混合存根和消息期望,否则会发生不好的事情 ......
回到你的问题,有两件事(或更多?)需要在这里指定:
get
on index
时,CustomersController会调用Customer#active_customers
。 在此规范中, Customer#active_customers
返回的内容并不重要。 active_customers
named_scope确实返回active
字段为true
客户。 我认为您正在尝试编号1.如果是,请删除整个存根,只需在测试中设置消息期望:
describe CustomersController do
it "should be successful and call Customer#active_customers" do
Customer.should_receive(:active_customers)
get :index
response.should be_success
end
end
在上面的规范中,您没有测试它返回的内容。 这没关系,因为这是规范的意图(虽然你的规范太靠近实现而不是行为,但这是一个不同的主题)。 如果您希望调用active_customers
特别返回某些内容,请继续将.and_returns(@whatever)
添加到该消息期望中。 故事的另一部分是测试active_customers
按预期工作(即:实际调用DB的模型规范)。
如果你想测试你收到一组客户记录,你应该在模拟周围有这样的数组:
Customer.stub_chain(:active_customers).and_return(@customers = [mock(Customer)])
stub_chain对我来说是最好的。
我有一个控制器呼叫
ExerciseLog.this_user(current_user).past.all
而且我能够像这样存根
ExerciseLog.stub_chain(:this_user,:past).and_return(@exercise_logs = [mock(ExerciseLog),mock(ExerciseLog)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.