Rspec:为什么我的模型一般不有效?

时间:2012-09-14 01:28:31

标签: ruby-on-rails ruby ruby-on-rails-3 factory-bot rspec-rails

问题与我的工厂有关,但我会先显示 location_spec.rb

require 'spec_helper'

describe Location do

  before(:each) do
    @location = FactoryGirl.build(:location)
  end

  subject { @location }

  describe "should be valid in general" do
    it { should be_valid }
  end

  describe "when user_id is not present" do
    before { @location.user_id = nil }
    it { should_not be_valid }
  end

  describe "when owner_id is not present" do
    before { @location.owner_id = nil }
    it { should_not be_valid }
  end
end

这是我的 factories.rb

FactoryGirl.define do
  factory :user do
    username   'user1'
    email      'user@example.com'
    timezone   'Eastern Time (US & Canada)'
    password   'testing'
  end

  factory :owner do
    name    'Owner One'
    user
  end

  factory :location do
    name 'Location One'
    about 'About this location'
    website 'http://www.locationone.com/'
    phone_number '12 323-4234'
    street_address 'Shibuya, Tokyo, Japan'


    association :owner, strategy: :build
  end
end

Location.rb

class Location < ActiveRecord::Base
  attr_accessible :about, :name, :owner_id, :phone_number,:street_address, :website
  belongs_to :owner
  belongs_to :user
  validates_presence_of :owner_id
  validates_presence_of :user_id
end

这是我得到的错误:

Failures:

  1) Location should be valid in general
     Failure/Error: it { should be_valid }
       expected valid? to return true, got false
    #./spec/models/location_spec.rb:53:in `block (3 levels) in <top (required)>'

我收到此错误,因为我正在为位置错误地构建关联我相信。关联应该是用户和所有者已经保存,而不仅仅是已经分配给两者的位置。我与我的工厂走在正确的轨道上还是别的什么?你觉得怎么样?

提前谢谢。

1 个答案:

答案 0 :(得分:3)

strategy: :build选项告诉FactoryGirl不要为FactoryGirl.createFactoryGirl.build实际保存关联的模型(所有者)。我认为这不是你想要的。

尝试将所有者的工厂线更改为owner,如下所示:

factory :location do
  name 'Location One'
  about 'About this location'
  website 'http://www.locationone.com/'
  phone_number '12 323-4234'
  street_address 'Shibuya, Tokyo, Japan'

  owner
end

这将是在实例化位置记录之前创建关联,以便该位置有效。如果您不这样做,那么对父(位置)的验证将失败,因为将不会分配owner_id(尚未创建所有者)。

<强>更新

您似乎也错过了user工厂中的location关联,它也会验证。所以将它添加到您的工厂也可以通过:

factory :location do
  name 'Location One'
  about 'About this location'
  website 'http://www.locationone.com/'
  phone_number '12 323-4234'
  street_address 'Shibuya, Tokyo, Japan'

  owner
  user
end

我认为应该这样做。