2012-09-13 53 views
1

由於位置屬於我的應用程序中的所有者和用戶,因此我希望基於這個事實構建它。所以在我的工廠是這樣的:Rspec:如何讓工廠有兩個協會?

FactoryGirl.define do 
    factory :user do 
    username 'user1' 
    email  '[email protected]' 
    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 

比我有我的規格/型號/ 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 

我希望這是因爲所有者首先創建用戶時,它不應該,比位置創建相同的用戶:

有了這一切,雖然這將返回我的測試失敗。那麼我該如何解決這個問題?

+1

您能否提供位置模型的完整定義? –

+0

@MattRogers好的,我現在就做了。 – LearningRoR

+1

你想要什麼樣的關聯?你想讓'Location'屬於一個用戶和一個擁有者嗎? –

回答

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  '[email protected]' 
    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 

感謝

+0

這就是我應該在'spec/models/location_spec.rb'中寫入的方法嗎?在我的應用程序中,「User」和「Owner」是完全不同的東西。用戶是他們的,所以我知道用戶添加了所有者和位置。這是一個獨特的設計。 – LearningRoR

+0

我的觀點是讓我的rspec測試的'Location'屬於所有者和用戶。我怎樣才能做到這一點? – LearningRoR

+0

@LearningRoR,表示你只是想爲Rspec做。在你的應用程序中,你沒有使用這種關係。我對嗎? –