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