2014-01-09 53 views
1

我正在嘗試爲我的用戶模型及其關聯創建一個工廠。但是,我似乎無法在Factory Girl代碼中獲得正確的語法。我已閱讀了Factory Girl文檔,但似乎無法找到任何有關我的特定用例的幫助。當我運行我的測試套件,我目前收到的錯誤是:工廠女孩 - 如何爲具有關聯的模型創建工廠?

undefined method `subscription_args' for #<FactoryGirl::SyntaxRunner... 

Trait not registered: valid_card_data 

這裏是我的模型和協會:

User.rb

has_one :subscription 
has_one :plan, :through => :subscription 
has_many :projects 

Project.rb

belongs_to :user 

Plan.rb

has_many :subscriptions 

Subscription.rb

belongs_to :plan 
belongs_to :user 

這裏是我的工廠女孩​​代碼:

FactoryGirl.define do 

    factory :user do 
    first_name "Joel" 
    last_name "Brewer" 
    email { "#{first_name}.#{last_name}@example.com".downcase } 
    password "foobar" 
    password_confirmation "foobar" 
    user_type "entrepreneur" 

    subscription { build(:subscription, subscription_args) } 

    after(:create) do |user| 
     user.subscription.save! 
    end 
    end 

    factory :subscription do 
    user 
    plan_id '4' 

    ## I am trying to access a helper method from support/utilities ## 
    ## This call to valid_card_data doesn't seem to be working... ## 

    stripe_card_token valid_card_data 
    email "[email protected]" 
    end 

    factory :project do 
    title "Sample Project" 
    user 
    end 
end 
+0

查看關聯下的https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md。 – kddeisz

+0

我試過通過文檔閱讀,我似乎無法得到它爲我的用例工作... –

回答

2

下面是我如何在過去做到了。當然不是唯一的方法:

(請注意我用的黃瓜)

require 'factory_girl' 

FactoryGirl.define do 

    factory :user do |f| 
    f.username 'superman' 
    end 

    factory :message do |f| 
    f.association :user 
    f.content 'Test message content' 
    end 

end 

這就證明,消息工廠應該消息關聯到用戶。哪個用戶?我建立在使用點:

steps.rb:

Given(/^there is a user$/) do 
    @user = FactoryGirl.create(:user) 
end 

Given(/^the user has posted the message "(.*?)"$/) do |message_text| 
    FactoryGirl.create(:message, :content => message_text, :user => @user) 
end 

When(/^I visit the page for the user$/) do 
    visit user_path(@user) 
end 

Then(/^I should see "(.*?)"$/) do |text| 
    page.should have_content(text) 
end 

我的做法,規定在使用點有意義的這種使用情況。例如Given是一個用戶(必須先建立用戶),並且該用戶發佈了一條消息(現在可以建立現有用戶和消息之間的關係)...

這可能會也可能不適合你,但這是我做到的。這可能會或可能不會幫助你,但這是希望。

+0

肯特,你真棒。在過去的兩天裏,我一直在竭盡全力想出這件事。非常感謝! –

1

有幾種方法可以做到這一點。這裏有一個例子:

after(:build) do |keyword, evaluator| 
    keyword.text = FactoryGirl.build(:keyword_text, :value => evaluator.keyword_text) 
end 

你不需要subscription_args - 當你調用這些工廠可以設置。

你在哪裏定義你的特質?

在我的工廠,他們看起來像這樣:

trait :with_category_associations do 
    .. 

對於您可能希望使用更復雜的關係:

after(:create) do |keyword, evaluator| 
    evaluator.categories.each do |category| 
     FactoryGirl.create(:join_inventory_keyword, final: keyword, category: category) 
    end 
    end