在我的所有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
我從來沒有知道它之前。謝謝:) – Chamnap
是的,但如果你使用stub_chain它不會失敗,當有人刪除此代碼並使用其他類型的方法來實現結果。 – Konrad