Rspec测试中nil类的未定义方法

Ben*_*Lee 4 ruby-on-rails associations rails-models model-associations ruby-on-rails-4

因此,我有一Game堂课,可以有很多Versions,每个课Version可以有很多GameStats。我有我的每个Version belongs_toa Game,每个GameStat belongs_toa Versionhas_one Game通过Versions。在我的测试中,当我测试对gameversion对象的响应以及对象相等性时,这些测试通过了,但是当我尝试通过调用引用对象时@stats.game,得到了#<NoMethodError: undefined method 'game' for nil:NilClass>。我在这里很困惑,因为我可以@stats.game在rails控制台中进行操作,但是在某种程度上它在测试中不存在。

相关的模型代码在这里:

class Game < ActiveRecord::Base
  has_many :versions, dependent: :destroy
  has_many :platforms, through: :versions
  has_many :game_stats, class_name: 'GameStats', through: :versions

  validates :name, presence: true
end

class GameStats < ActiveRecord::Base
  belongs_to :version

  has_one :game, through: :version

  validates :version_id, presence: true
end

class Version < ActiveRecord::Base
  belongs_to :game
  belongs_to :platform

  has_many :game_stats, class_name: 'GameStats'

  validates :game_id, presence: true
  validates :platform_id, presence: true
end
Run Code Online (Sandbox Code Playgroud)

我的RSpec文件(相关部分)如下所示:

describe GameStats do
  let!(:game) { FactoryGirl.create(:game) }
  let!(:platform) { FactoryGirl.create(:platform) }
  let!(:version) { FactoryGirl.create(:version, game: game, platform: platform) }

  before do
    @stats = FactoryGirl.create(:game_stats, version: version)
  end

  subject { @stats }

  ....

  it { should respond_to(:version) }
  it { should respond_to(:game) }

  its(:version) { should eq version }
  its(:game) { should eq game }

  ...

  describe "2 different days stats should have the same game" do
    before do
      @stats.save
      @another_stats = FactoryGirl.create(:game_daily_stats, version: version, datestamp: Date.yesterday)
      @another_stats.save
    end
    expect(@another_stats.game).to eq @stats.game
  end
end
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么会发生此错误?

我在使用Ruby 2.0.0-p247的Rails 4.0.0上,使用RSpec-rails 2.14.0,factory_girl_rails 4.2.1。

apn*_*ing 5

更换:

expect(@another_stats.game).to eq @stats.game
Run Code Online (Sandbox Code Playgroud)

与:

it 'description' do
  expect(@another_stats.game).to eq @stats.game
end
Run Code Online (Sandbox Code Playgroud)

顺便说一句,使用let而不是实例变量