【问题标题】:Undefined method for nil class in Rspec testRspec测试中nil类的未定义方法
【发布时间】:2013-10-29 09:17:17
【问题描述】:

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

相关型号代码在这里:

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

而我的 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

有人知道为什么会发生这个错误吗?

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 associations model-associations rails-models


    【解决方案1】:

    替换:

    expect(@another_stats.game).to eq @stats.game
    

    与:

    it 'description' do
      expect(@another_stats.game).to eq @stats.game
    end
    

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

    【讨论】:

    • 谢谢。那行得通,我不敢相信我错过了。我太粗心了。
    • 所有 rspec 用户总有一天会这样做;)
    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2023-03-19
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多