rspec association test only works in one direction

一世执手 提交于 2020-01-07 03:37:07

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/3306389/rspec-association-test-only-works-in-one-direction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!