So, I have a Game class that can have many Versions, and each Version can have many GameStats. I have my Each Version belongs_to a Game, and each GameStat belongs_to a Version and has_one Game through the Versions. In my tests, when I test for response to the game and version objects, and for object equality, those tests pass, but when I try to reference the object by calling @stats.game, I get a #<NoMethodError: undefined method 'game' for nil:NilClass>. I'm very confused here, because I could do a @stats.game in the rails console, but it somehow does not exist in the test.
The relevant model code is here:
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
And my RSpec file (the relevant parts) is like so:
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
Does anyone have any idea why this error is happening?
I'm on Rails 4.0.0, with Ruby 2.0.0-p247, using RSpec-rails 2.14.0, factory_girl_rails 4.2.1.
replace:
expect(@another_stats.game).to eq @stats.game
with:
it 'description' do
  expect(@another_stats.game).to eq @stats.game
end
BTW, use let instead of instance variables
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With