ruby-on-rails - 在 Rails 中测试范围链的最佳方法

标签 ruby-on-rails testing scope mocking stub

在我所有的 ruby​​ on rails 应用程序中,我尽量不在 Controller 中使用数据库,因为它们应该独立于持久性类。我改用模拟。

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

但是如果 Controller 包含更复杂的范围,比如:

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

最佳答案

你可以为此使用 stub_chain 方法。

类似于:

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

只是一个例子。

关于ruby-on-rails - 在 Rails 中测试范围链的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10863675/

相关文章:

linux - 从 .iso 修改 index.php

php - CodeIgniter,将数据从模型传递到 Controller 以在 View 中使用

c++ - 'new'和 'delete'不同范围内的合法性和道德性

ruby-on-rails - Rails,编写模块。存储设置在哪里?

ruby-on-rails - ActiveRecord 中的 Postgres 插入错误

ruby-on-rails - 重置密码时跳过Devise模型中某些成员的验证

java - 使用 JUnit 对 Webview 进行单元测试

ruby-on-rails - ActiveRecord 有 Lint 吗?

ruby-on-rails - rails link_to 使用 get 而不是 post