在Rails中测试作用域链的最佳方法

时间:2012-06-02 15:41:10

标签: ruby-on-rails testing scope mocking stub

在我的ruby on rails应用程序中,我尝试不在控制器中使用数据库,因为它们应该独立于持久性类。我反而使用了嘲笑。

以下是rspec和rspec-mock的示例:

class CouponsController < ApplicationController
  def index
    @coupons = Coupon.all
  end
end

require 'spec_helper'
describe CouponsController do
  let(:all_coupons) { mock } 
  it 'should return all coupons' do
    Coupon.should_receive(:all).and_return(all_coupons)
    get :index
    assigns(:coupons).should == all_coupons
    response.should be_success
  end
end

但是如果控制器包含更复杂的范围,例如:

class CouponsController < ApplicationController
  def index
    @coupons = Coupon.unredeemed.by_shop(shop).by_country(country)
  end
end

你知道测试simillar范围链的任何好方法吗?

我认为以下测试看起来不太好:

require 'spec_helper'
describe CouponsController do
  it 'should return all coupons' do
    Coupon.should_receive(:unredeemed).and_return(result = mock)
    result.should_receive(:by_shop).with(shop).and_return(result)
    result.should_receive(:by_country).with(country).and_return(result)
    get :index
    assigns(:coupons).should == result
    response.should be_success
  end
end

2 个答案:

答案 0 :(得分:6)

您可以使用stub_chain方法。

类似的东西:

Coupon.stub_chain(:unredeemed, :by_shop, :by_country).and_return(result)

只是一个例子。

答案 1 :(得分:0)

rspec > 3使用以下语法:

expect(Converter).to receive_message_chain("new.update_value").with('test').with(no_args)

而不是stub_chain

详细了解消息链in the documenation