0

这个问题与我的工厂有关,但我会先展示我的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

这是我的工厂.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

位置.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)>'

我收到此错误是因为我为我相信的位置错误地建立了关联。关联应该是用户和所有者已经保存,而不仅仅是已经分配给两者的位置。我的工厂是否走在正确的轨道上,还是其他原因?你怎么看?

先感谢您。

4

1 回答 1

3

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

尝试将与所有者的 factory line 更改为 just 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

我认为应该这样做。

于 2012-09-14T02:08:19.660 回答