2012-06-02 18 views
2

在我的所有ruby on rails應用程序中,我嘗試在控制器中不使用數據庫,因爲它們應該獨立於持久性類。我用嘲笑來代替。在Rails中測試作用域鏈的最佳方法

這裏是RSpec的和RSpec,模擬的例子:

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 

回答

6

您可以使用該方法stub_chain

喜歡的東西:

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

只是一個例子。

+0

我從來沒有知道它之前。謝謝:) – Chamnap

+1

是的,但如果你使用stub_chain它不會失敗,當有人刪除此代碼並使用其他類型的方法來實現結果。 – Konrad

0

隨着rspec > 3使用的語法如下:

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

,而不是stub_chain

閱讀更多關於消息鏈in the documenation

相關問題