gpt4 book ai didi

ruby-on-rails - Rspec 测试中 nil 类的未定义方法

转载 作者:行者123 更新时间:2023-12-04 06:36:34 26 4
gpt4 key购买 nike

所以,我有一个 Game可以有很多的类 Versions , 和每个 Version可以有很多GameStats .我有我的每一个 Version belongs_to Game , 和每个 GameStat belongs_to Versionhas_one Game通过 Versions .在我的测试中,当我测试对 game 的响应时和 version对象,对于对象相等,这些测试通过了,但是当我尝试通过调用 @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

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

最佳答案

代替:

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

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

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

关于ruby-on-rails - Rspec 测试中 nil 类的未定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19654020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com