从 Rspec 读取 Rails 环境变量



我有一个 rspec 测试来验证一个根据 rails 版本工作的函数。所以在我的代码中,我计划使用 Rails::VERSION::String 来获取 rails 版本。

在测试之前,我尝试像这样显式设置rails版本

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

但是当我运行测试时,rspec 似乎找不到Rails变量并给了我错误

uninitialized constant Rails (NameError)

所以我在这里可能错过了什么,提前感谢

执行此操作

的最佳方法是将 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

最新更新