문제

I have the following model:

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

for which I wrote this test:

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

Validation is not working because it:

"Cannot find Team with id 1"

These are the factories:

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
도움이 되었습니까?

해결책

It looks like the error is probably happening inside the description function, because you're not setting the id correctly.

Try changing your code to the following:

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)

This should set the id's in the game model.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top