3

所以,我有一個Game類可以有很多Versions,並且每個Version可以有很多GameStats。我有我的每個Versionbelongs_to a Game,並且每個GameStatbelongs_to a Versionhas_oneGame通過Versions。在我的測試中,當我測試應對gameversion對象,併爲對象的平等,這些測試都通過了,但是當我試圖通過調用@stats.game引用對象,我得到一個#<NoMethodError: undefined method 'game' for nil:NilClass>。我在這裏非常困惑,因爲我可以在rails控制檯中執行@stats.game,但它在測試中不存在。在Rspec測試中未定義的nil類的方法

相關模型的代碼是在這裏:

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 

有沒有人有這個原因發生錯誤的任何想法?

我on Rails的4.0.0,使用Ruby 2.0.0-P247,使用RSpec的護欄2.14.0,factory_girl_rails 4.2.1。

回答

4

取代:

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

有:

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

BTW,使用let代替實例變量的

+0

謝謝。這工作,我不相信我錯過了。這對我來說很粗心。 –

+0

所有rspec用戶在某一天或某一天完成此操作;) – apneadiving

相關問題