2

Railsのバージョンに応じて機能する機能を検証するrspecテストがあります。したがって、私のコードでは Rails::VERSION::String を使用して Rails のバージョンを取得する予定です。

テストの前に、このようにレールのバージョンを明示的に設定しようとしました

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

しかし、テストを実行すると、rspecがRails変数を見つけられず、エラーが発生するようです

uninitialized constant Rails (NameError)

だから私はここで何が欠けているのかもしれません、事前に感謝します

4

1 に答える 1

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
于 2012-09-11T19:40:10.320 に答える