【发布时间】:2013-10-29 09:17:17
【问题描述】:
所以,我有一个Game 类,它可以有很多Versions,每个Version 可以有很多GameStats。我有我的每个Version belongs_to 一个Game,每个GameStat belongs_to 一个Version 和has_one Game 通过Versions。在我的测试中,当我测试对game 和version 对象的响应以及对象相等性时,这些测试通过了,但是当我尝试通过调用@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