2014-04-10 53 views
0

我有以下型號:rspec的不能找到FactoryGirl ID創建的模型

class Game < ActiveRecord::Base 
    validates_presence_of :team_b_id, :team_a_id 

    def description 
    Team.find(team_a_id).name + " vs " + Team.find(team_b_id).name 
    end 
end 

爲至極我寫這個測試:

describe Game do 
    ... 
    it "returns game description" do 
    game = FactoryGirl.create(:game) do 
     team_a_id = FactoryGirl.create(:team, name: "Team A").id 
     team_b_id = FactoryGirl.create(:team, name: "Team B").id 
    end 
    game.description.should == team_a.name + " vs " + team_b.name 
    end 
end 

驗證是不工作,因爲它「無法與ID找到團隊1" 這些工廠:

FactoryGirl.define do 
    factory :game do |f| 
    f.team_a_id { 1 } 
    f.team_b_id { 2 } 
    end 
end 

FactoryGirl.define do 
    factory :team do |f| 
    f.name { "Team Name" } 
    end 
end 

感謝

+0

ruby​​ 4,factory_girl_rails gem – ntonnelier

+0

您已經定義了'f.team_a_id {1}'和'f.team_b_id {2}',所以當您調用FactoryGirl.create(:team,name:「Team A」)時,會自動接受這兩個定義值,所以它既有team_a_id也有team_b_id,所以在這裏沒有關於驗證的問題 –

回答

0

看起來好像錯誤可能發生在描述函數內部,因爲你沒有正確設置id。

試着改變你的代碼如下:

team_a_id = FactoryGirl.create(:team, name: "Team A").id 
team_b_id = FactoryGirl.create(:team, name: "Team B").id 

game = FactoryGirl.create(:game, team_a_id: team_a_id, team_b_id: team_b_id) 

這應該設置id在遊戲中的模型。

相關問題