我无法找到这样的情况。我有一个模型,它具有如此定义的命名范围:

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我想做什么。

有帮助吗?

解决方案

我认为在存根消息期望。消息期望基本上是存根,您可以在其中设置所需的预设响应,但它们还会测试要测试的代码进行的调用。相比之下,存根只是方法调用的固定响应。但是,不要在相同的方法和测试中混合带有消息期望的存根,否则会发生坏事......

回到你的问题,有两件事(或更多?)需要在这里指明:

  1. 当您在 index 上执行 get 时,CustomersController会调用 Customer #active_customers 。在此规范中返回 Customer#active_customers 并不重要。
  2. active_customers named_scope实际上确实返回 active 字段为 true 的客户。
  3. 我认为您正在尝试编号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归因
不隶属于 StackOverflow
scroll top