Setting Protected Attributes with FactoryGirl

FactoryGirl will not set my protected user.confirmed attribute. What is the best practice here?

 Factory.define :user do |f| f.name "Tim" # attr_accessible -- this works f.confirmed true # attr_protected -- doesn't work end 

I can do @user.confirmed = true after using my factory, but this is many repetitions in many tests.

+8
ruby-on-rails ruby-on-rails-3 factory-bot
source share
3 answers

Using hook after_create works:

 Factory.define :user do |f| f.name "Tim" f.after_create do |user| user.confirmed = true user.save end end 
+10
source share

You will need to pass it to the hash when creating the user, as FactoryGirl protects it from mass assignment.

 user ||= Factory(:user, :confirmed => true) 
+3
source share

Another approach is to use Rails built-in roles, such as:

 #user.rb attr_accessor :confirmed, :as => :factory_girl 

When a bulk assignment FactoryGirl transfers this role, making this pattern possible.

Pros: Keeps factories fast, simple and clean (less code in callbacks)
Cons: You change your model code for your tests :(

Some unverified suggestions for accessing Con:

  • You can re-open the class just above the factory.
  • You can reopen the class in [test | spec] _helper
0
source share

All Articles