views:

103

answers:

1

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?

A: 

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

Marcus Derencius