我一直无法找到任何此类情况。我定义它有一个名为范围的模型正是如此:在RSpec控制器中扼杀named_scope
class Customer < ActiveRecord::Base
# ...
named_scope :active_customers, :conditions => { :active => true }
end
和我试图存根它在我的控制器规格:
# 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我想做什么。
谢谢您的解释(我在下面的一个RSpec教程,但是它是如何显示到用模拟/存根执行操作)。然而,当我尝试你发布的代码时,我得到了同样的错误: expected:active_customers(任何参数)一次,但收到0次。尽管在CustomersController#index中调用了Customer.active_customers。 –
2009-10-28 19:57:55
对不起,我的坏。对'get:index'的调用应该在消息期望之后。我正在纠正答案,以便期望成为规范中的第一行。 – hgmnz 2009-10-28 20:45:32
好的,现在正在工作。我习惯于正常的测试过程,get:index在测试之前出现,所以这似乎是问题。它与RSpec相反。我想我需要更多练习RSPec。谢谢! – 2009-10-29 12:50:11