在RSpec控制器中对named_scope进行存根

Way*_*ina 2 rspec ruby-on-rails

对于像这样的情况,我找不到任何东西.我有一个模型,它具有如此定义的命名范围:

class Customer < ActiveRecord::Base
  # ...
  named_scope :active_customers, :conditions => { :active => true }
end
Run Code Online (Sandbox Code Playgroud)

我试图在我的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
Run Code Online (Sandbox Code Playgroud)

这不起作用并且失败,说客户期望active_customers但是收到它0次.在我的实际控制器中,我有索引操作@customers = Customer.active_customers.为了让这个工作,我错过了什么?可悲的是,我发现编写代码比编写测试/规范更容易,并且写了因为我知道规范描述的内容,而不是如何告诉RSpec我想做什么.

hgm*_*mnz 8

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

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

  1. Customer#active_customers当您执行操作时,CustomersController会调用getindex.Customer#active_customers在这个规范中返回什么并不重要.
  2. active_customersnamed_scope确实事实上回报客户,其中activetrue.

我认为您正在尝试编号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
Run Code Online (Sandbox Code Playgroud)

在上面的规范中,您没有测试它返回的内容.这没关系,因为这是规范的意图(虽然你的规范太靠近实现而不是行为,但这是一个不同的主题).如果您希望调用active_customers特别返回某些内容,请继续添加.and_returns(@whatever)该消息预期.故事的另一部分是测试它是否active_customers按预期工作(即:实际调用DB的模型规范).