2012-03-02 15 views
0

我正在寫一個可以使用和不使用導軌的寶石。在一些地方我使用代碼如如何在rspec中存留:: Rails.root?

path = Rails.root if defined?(::Rails) 

我想用rspec測試這個邏輯。我曾嘗試磕碰它像

stub(:"::Rails").should_receive(:root).and_return("/rails") 

,但這並不能使defined?(::Rails)評估爲true

回答

2

即使defined?(::Rails)評估爲true,仍需要一個Rails對象來注入方法存根。可能有幾種方法可以做到這一點,以下是我的首選方法一個例子:

before(:each) do 
    unless defined?(::Rails) 
    @mocked_rails_class = true 
    class ::Rails 
    end 
    end 
end 

it do 
    ::Rails.should_receive(:root).and_return('/rails') 
    your_method.should == '/rails' 
end 

after(:each) do 
    # Clean up the Rails class if it's generated by the test case. 
    Object.send(:remove_const, :Rails) if @mocked_rails_class 
end 

我不知道這是否適用於所有版本的紅寶石,但至少它可以在紅寶石1.9.x中工作

+0

這工作很好!謝謝! – 2012-03-02 03:34:45

+1

對我來說,它只是'未定義的方法'should_receive'for Rails:Module' – Michael 2014-06-11 14:04:40

+0

在較新的Rspec中,您需要用'expect(whatever).to'替換'whatever.should'的所有實例。 – 2014-09-07 13:07:23