2012-07-02 81 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