Setting protected attributes with FactoryGirl
Asked Answered
A

3

8

FactoryGirl won't set my protected attribute user.confirmed. What's 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 a @user.confirmed = true after using my factory, but that's a lot of repetition across a lot of tests.

Attune answered 18/1, 2012 at 5:29 Comment(0)
A
10

Using an after_create hook works:

Factory.define :user do |f|
  f.name "Tim"
  f.after_create do |user|
    user.confirmed = true
    user.save
  end
end 
Attune answered 18/1, 2012 at 19:4 Comment(1)
Great find. More recent of versions of factory girl changed the syntax to after(:create). See getting started guideUptown
D
3

You would have to pass it into the hash when you create the user since FactoryGirl is protecting it from mass-assignment.

user ||= Factory(:user, :confirmed => true)
Dupe answered 18/1, 2012 at 6:1 Comment(2)
Works for me on FactoryGirl 2.1.0.Dupe
I'm using 2.3.2, so that could be it but it seems unlikelyAttune
F
0

Another approach is to use Rails' built in roles like this:

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

When mass-assigning FactoryGirl broadcasts this role, making this pattern possible.

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

Some untested suggestions to address the Con:

  • You could re-open the class just above your factory.
  • You could re-open the class in a [test|spec]_helper
Formwork answered 3/6, 2013 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.