【问题标题】:Best approach to test scope chains in Rails在 Rails 中测试范围链的最佳方法
【发布时间】:2012-06-02 15:41:10
【问题描述】:

在我所有的 ruby​​ on rails 应用程序中,我尽量不在控制器中使用数据库,因为它们应该独立于持久性类。我用 mocking 代替。

这是 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

你知道测试类似作用域链的好方法吗?

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

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

【问题讨论】:

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


    【解决方案1】:

    您可以使用stub_chain 方法。

    类似:

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

    只是一个例子。

    【讨论】:

    • 我以前从来不知道。谢谢:)
    • 是的,但是如果你使用 stub_chain,当有人删除这段代码并使用其他类型的方法来达到结果时,它不会失败。
    【解决方案2】:

    rspec &gt; 3 使用以下语法:

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

    而不是stub_chain

    阅读有关消息链的更多信息in the documenation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多