2012-01-07 24 views
2

我有一個使用RSpec測試的Rails 3應用程序。我已經使用外部類MustMock作爲模擬Rails控制器規範中的外部類

class FooController < ApplicationController 
    def myaction 
    mockme = MustMock.new 
    @foobar = mockme.do_something 
    end 
end 

我怎樣才能最好地嘲笑的MustMock實例在我的控制器規格控制器?

回答

5
describe FooController do 
    specify :myaction do 
    MustMock.should_receive(:new) 
      .and_return(stub :do_something => :something) 
    get :myaction 
    assigns[:foobar].should == :something 
    end 
end 
+0

+1,我喜歡這個塊的形式很多。我要複製你的風格! :) – iain 2012-01-07 03:24:43

2

你可以試試這個:

it "does something in myaction" do 
    my_stub = stub() 
    my_stub.should_receive(:do_something).once.and_return(:foobar) 
    MustMock.stub(:new => my_stub) 
    get :myaction 
    response.should be_success 
end 
+0

一個小問題 - 我傾向於把'response.should be_success'在shared_example,因爲這將是如此普遍希望,對於一個頁。 YMMV – iain 2012-01-07 03:22:31

+1

是的,有幾種方法可以改進測試。我懷疑OP的控制者行動更爲複雜,他/她將問題歸結爲最小可證明的行動。 – Finbarr 2012-01-07 03:24:03

+0

完全同意,我確實意味着次要:) – iain 2012-01-07 03:26:08