rspec关联测试仅在一个方向上起作用 [英] rspec association test only works in one direction

查看:86
本文介绍了rspec关联测试仅在一个方向上起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已升级到Rails 3和RSpec 2,并且我的RSpec测试之一停止了工作:

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的值为nil,但location.job是正确的.如果我摆脱了validates_associated :location,它也可以正常工作.谁能解释为什么这行不通?

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?

推荐答案

作业已在内存中.或在创建位置后重新加载它,或使用lambda/expect.例如:

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

此处的更多信息: http://rspec .rubyforge.org/rspec/1.3.0/classes/Spec/Matchers.html#M000168

这篇关于rspec关联测试仅在一个方向上起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆