2

私のすべてのRubyonRailsアプリでは、永続性クラスから独立している必要があるため、コントローラーでデータベースを使用しないようにしています。代わりにモックを使用しました。

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
4

2 に答える 2

7

あなたはそのためstub_chainの方法を使うことができます。

何かのようなもの:

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

ほんの一例です。

于 2012-06-02T15:49:45.377 に答える