我有一个rspec测试来验证一个根据rails版本工作的函数。所以在我的代码中,我打算使用Rails :: VERSION :: String来获取rails版本。
在测试之前,我试图明确设置这样的rails版本
Rails::VERSION = "2.x.x"
但是当我运行测试时,似乎rspec无法找到Rails
变量并给我错误
uninitialized constant Rails (NameError)
所以我在这里可能缺少什么,提前谢谢
答案 0 :(得分:0)
执行此操作的最佳方法是将rails版本检查封装在您控制的代码中,然后将您要执行的不同测试值存根。
例如:
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