0

I upgraded to Rails 3 and RSpec 2 and one of my RSpec tests stopped working:

# Job.rb
class Job < ActiveRecord::Base
  has_one :location
  belongs_to :company

  validates_associated :location
end

# Location.rb
class Location < ActiveRecord::Base 
  belongs_to :job
end

# job_spec.rb
describe Job, "location" do
  it "should have a location" do
    job = Factory(:job)
    location = Factory(:location, :job_id => job.id)

    location.job.should == job      #true
    job.location.should == location #false
  end                                           
end

job.location evaluates to nil but location.job is correct. It also works fine if I get rid of validates_associated :location. Can anyone explain why this doesn't work?

choxi
  • 455
  • 4
  • 18
  • does your factory `create` or `build` by default? I would define another factory `:job_with_a_location` where you use the association-builders to make sure it is filled up correctly. But that does not explain why this doesn't work anymore :) – nathanvda Jul 22 '10 at 09:37

1 Answers1

2

job is already on memory. or you reload it after creating location, or use lambda/expect. eg:

describe Job, "location" do
  it "should have a location" do
    job = Factory(:job)
    location = Factory(:location, :job_id => job.id)
    job.reload
    location.job.should == job      #true
    job.location.should == location #false
  end 

  it "should have a location" do
    job = Factory(:job)

    expect {
      location = Factory(:location, :job_id => job.id) 
    }.to change(job, :location).to(location)
    lambda {
      location = Factory(:location, :job_id => job.id) 
    }.should change(job, :location).to(location)

    location.job.should == job      #true         
  end                                          
end

more info here: http://rspec.rubyforge.org/rspec/1.3.0/classes/Spec/Matchers.html#M000168