2012-07-18 40 views
6

我要幹在我廠創建/建立後鉤:DRY FactoryGirl後創建/建立掛鉤

FactoryGirl.define do 

    factory :poll do 

    sequence :title do |n| 
     "MyPollTitle#{n}" 
    end 
    sequence :description do |n| 
     "MyPollDescription#{n}" 
    end 
    user 

    factory :poll_with_answers do 

     ignore do 
     answers_count 2 
     end 

     after(:build) do |poll, evaluator| 
     evaluator.answers_count.times do 
      poll.answers << build(:answer, poll: poll) 
     end 
     end 

     after(:create) do |poll, evaluator| 
     evaluator.answers_count.times do 
      poll.answers << create(:answer, poll: poll) 
     end 
     end 
    end 
    end 
end 

我面臨的問題是,它似乎我不能定義在FG的方法呢?想法如何幹這件事?

回答

6

首先,after(:create)隱式調用after(:build),至少在最新版本的FactoryGirl的:

後(:編譯) - 工廠建成後調用(通過FactoryGirl.build,FactoryGirl.create)

https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#callbacks

所以你的情況,下面的代碼應該是足夠了:

after(:build) do |poll, evaluator| 
    evaluator.answers_count.times do 
    poll.answers << build(:answer, poll: poll) 
    end 
end 

但是,當您使用build_stubbed()而不是build()時,不會觸發after(:build),這是我在遇到此線程時正在嘗試執行的操作。幹這個代碼,事實證明,你可以使用callback()方法來調用多個方法相同的塊:

factory :user do 
    callback(:after_build, :after_stub) do |user| 
    do_something_with(user) 
    end 
end 
1

這可能是一個把戲,但你可以在第二工廠創建拉姆達:

factory :poll_with_answers do 
    ignore do 
    answers_count 2 
    end 

    make_answers = lambda do |poll, evaluator, method| 
    evaluator.answers_count.times do 
     poll.answers << send(method, :answer, poll: poll) 
    end 
    end 

    after(:build) do |poll, evaluator| 
    make_answers.call poll, evaluator, :build 
    end 

    after(:create) do |poll, evaluator| 
    make_answers.call poll, evaluator, :create 
    end 
end 

我不是這種模式在所有的幸福,但至少它乾的東西了。

+0

它應該做的伎倆。它與你的代碼非常相似,所以如果評估器在lambda版本中爲零,那麼它也應該在你的版本中爲零。你能不能把我的原始工作代碼和得到nils的代碼(也就是棧跟蹤)都歸爲一類。我目前沒有足夠的信息進行調試。 – 2012-07-18 22:16:11

+0

你不需要在這方面投入更多的工作,這並不重要,我基本上只是想檢查是否有一個快捷方式。無論如何,我在https://gist.github.com/3140033上看到了模型,剩下的是1:1。 – wintersolutions 2012-07-19 00:51:40

+0

好吧,不用擔心,但檢查完代碼後,我不知道「評估者」是什麼:) – 2012-07-19 07:45:48