1

ロケーションはアプリケーションの所有者とユーザーに属しているため、この事実に基づいて構築したいと考えています。したがって、私の工場では次のようになります。

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'
    owner
    user
  end
end

私のspec/models/location_spec.rbよりも

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

私のモデルのlocation.rbより

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

注:owner_id選択可能ですのでご利用いただけます。

このすべてを使用すると、次のようにテストの失敗が返されます。

Failure/Error: @location = FactoryGirl.build(:location) 
     ActiveRecord::RecordInvalid: 
       Validation failed: Email has already been taken, Email has already been taken, Username

これは、所有者が最初にユーザーを作成すべきではないときに最初にユーザーを作成し、場所が同じユーザーを作成するためだと思います。では、どうすればこれを回避できますか?

4

2 に答える 2

0

工場にシーケンスを追加する必要がありました。それだけでした。https://github.com/thoughtbot/factory_girl/wiki/使い方

factory :user do
  sequence(:username)  { |n| "User#{n}" }
  sequence(:email)     { |n| "User#{n}@example.com"}  
  timezone   'Eastern Time (US & Canada)'
  password   'testing'
end
于 2012-09-14T22:15:50.457 に答える
0

このような関連付けを書くことができます

User
has_one :locations

Owner
has_one :locations

Location
belongs_to :users
belongs_to :owner

この関連付けは機能しますが、 FactoryGirlとは関係ありません。また、所有者を別の分野にしたいのに、場所が別のユーザーと所有者に属している場合、この設計は良くないと感じています。ユーザー モデルにフィールド is_owner を追加することでこれを行うこともできます。所有者用に別のモデルを作成する必要はありません。

現在の情報では、これだけのことが言えます。

また、ファクトリーガールの実装を変更してみてください

FactoryGirl.define  do
  factory :user, :class=> User do |f|    
    f.username   'user1'
    f.email      'user@example.com'
    f.timezone   'Eastern Time (US & Canada)'
    f.password   'testing'  
  end
end

FactoryGirl.define do
  factory :owner do, :class => Owner do |f|
    f.name    'Owner One'
    f.about   ''
    f.private false    
  end 
end

ありがとう

于 2012-09-13T04:35:11.207 に答える