DRY FactoryGirl after creating / assembling hooks

I want DRY up after creating / building interceptors in my Factory:

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 

The problem I am facing is that it seems that I cannot define methods in FG? Idea how to do this?

+6
source share
2 answers

First, after(:create) implicitly calls after(:build) , at least in recent versions of FactoryGirl:

after (: build) - called after creating the factory (via FactoryGirl.build, FactoryGirl.create)

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

So, in your case, the following code should suffice:

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

However, after(:build) does not start when you use build_stubbed() instead of build() , and this is what I tried to do when I came across this thread. To unload this code, you can use the callback() method to call the same block for several methods:

 factory :user do callback(:after_build, :after_stub) do |user| do_something_with(user) end end 
+6
source

It may be a cheap trick, but you can create a lambda in the second factory:

 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 

I'm not quite happy with this model, but at least it's DRY stuff.

+1
source

Source: https://habr.com/ru/post/920769/


All Articles