2012-07-02 71 views
2

我有一個rspec測試來驗證一個函數,這取決於rails版本。所以在我的代碼中,我計劃使用Rails :: VERSION :: String來獲取rails版本。閱讀rails env變量rspec

在測試之前,我想明確地設置導軌版本這樣

Rails::VERSION = "2.x.x" 

但是當我運行測試好像rspec的找不到Rails變量,給我的錯誤

uninitialized constant Rails (NameError) 

所以,我可能會錯過這裏,在此先感謝

+1

如果要設置特定的軌道版本,那麼你可以做它在'gemfile'中? : - /你爲什麼這樣做? – uday

+0

您好,感謝您的回覆,原因是我想模擬我的測試用例中的不同rails版本,不管目前的項目 – sameera207

回答

0

要做到這一點的最佳方法是封裝軌道版本檢查代碼,你con trol,然後根據您想要鍛鍊的不同測試值進行測試。

例如:

module MyClass 
    def self.rails_compatibility 
    Rails.version == '2.3' ? 'old_way' : 'new_way' 
    end 
end 

describe OtherClass do 
    context 'with old_way' do 
    before { MyClass.stubs(:rails_compatibility => 'old_way') } 
    it 'should do this' do 
     # expectations... 
    end 
    end 

    context 'with new_way' do 
    before { MyClass.stubs(:rails_compatibility => 'new_way') } 
    it 'should do this' do 
     # expectations... 
    end 
    end 
end 

或者,如果你的版本的邏輯是複雜的,你應該踩滅了一個簡單的包裝:

module MyClass 
    def self.rails_version 
    ENV['RAILS_VERSION'] 
    end 

    def self.behavior_mode 
    rails_version == '2.3' ? 'old_way' : 'new_way' 
    end 
end 

describe MyClass do 
    context 'Rails 2.3' do 
    before { MyClass.stubs(:rails_version => '2.3') } 
    it 'should use the old way' do 
     MyClass.behavior_mode.should == 'old_way' 
    end 
    end 

    context 'Rails 3.1' do 
    before { MyClass.stubs(:rails_version => '3.1') } 
    it 'should use the new way' do 
     MyClass.behavior_mode.should == 'new_way' 
    end 
    end 
end 
+0

中的rails版本多少,這對我有很大的幫助 – sameera207