2009-08-22 223 views
0

我想模擬一個正在傳遞給另一個對象的對象,並且沒有成功。有人能告訴我我做錯了什麼嗎?rspec模擬問題

class Fetcher 
    def download 
    return 3 
    end 
end 

class Reports 
    def initialize(fetcher) 
    @fetcher = fetcher 
    end 
    def status 
    @fetcher.download 
    end 
end 


describe Reports do 
    before(:each) do 
    end 

    it "should get get status of 6" do 
    Fetcher.should_receive(:download).and_return(6) 
    f = Reports.new(Fetcher.new) 
    f.status.should == 6 
    end 
end 

該規範仍然報告狀態返回3,不是我的意圖6.

當然我在這裏失去了一些東西。有什麼想法嗎?

回答

1

在測試中,我認爲你正在試圖做的是這樣的(我認爲)

it '...' do 
    some_fetcher = Fetcher.new 
    some_fetcher.should_receive(:download).and_return(6) 

    f = Reports.new(some_fetcher) 
    f.status.should == 6 
end 

當你說Fetcher.should_receive(:下載),你說的CLASS應該接收打電話'下載',而不是類的實體...

希望這有助於!如果不清楚,請告訴我!

+0

謝謝,就是這樣。但是......兩件事。 1.爲什麼Fetcher的實例不會繼承對類的更改?如果我向Fetcher添加了一個新的方法,然後實例化它,它會有這種方法,不是嗎? 2.我在rspec的Peepcode screencast上得到了上面的代碼。原始代碼是針對Rails模型的,如下所示: def mock_feed(zipcode,how_many = 1) xml = ... Weather.should_receive(:open).exactly(how_many).times。 (「http://weather.yahooapis.com/forecastrss?p=#{zipcode}」)。 and_return(xml) end 爲什麼他的類修改工作,而不是我的? – 2009-08-22 03:16:29

+0

對於#1,你可以做到這一點,但是如果不能保證在正確的時間實例化第二個類,那麼很容易出現問題。您可能不想按照您所描述的方式定義新方法,而是嘗試使用「instance_eval」。 所以,如果你想添加一個方法弗萊徹,你可以這樣做: Fletcher.class_eval做 高清some_method ... 結束 結束 一些其他人比我能解釋這更好的。這裏有一些鏈接: http://bmorearty.wordpress.com/2009/01/09/fun-with-rubys-instance_eval-and-class_eval/ #2,我不能解決問題。你能再試一次嗎? – btelles 2009-08-23 02:11:16

0

根據新的語法進行更新。

subject(:reports) { described_class.new(fetcher) } 
let(:fetcher}  { double("Fetcher") } 

describe "#status" do 
    it "gets status of 6" do 
    fetcher.stub(download: 6) 
    expect(reports.status).to == 6 
    end 
end