Laran Evans
Laran Evans

Reputation: 1313

References inside factory_girl factories don't work properly

Factory.define :person do |p|
  p.first_name { User.generate_activation_code(6) }
  p.last_name { User.generate_activation_code(6) }
  p.username { "p#{first_name}_#{last_name}" }
  p.email { "#{username}@mail.com" }
  p.password { "password" }
  p.password_confirmation { "password" }
end

Gives this error:

undefined local variable or method first_name' for main:Object (NameError) ./test/factories/user_factories.rb:4 ./features/step_definitions/generic_steps.rb:3 ./features/step_definitions/generic_steps.rb:2:in each' ./features/step_definitions/generic_steps.rb:2:in /^these (.+) records$/' features/transaction_import.feature:7:in Given these person records'

Here's my configuration (Ruby 1.8.7)

Using cucumber (0.10.0) 
Using cucumber-rails (0.3.2) 
Using factory_girl (1.3.3) 
Using railties (3.0.3) 
Using factory_girl_rails (1.0.1) 
Using rails (3.0.3) 
Using rspec-core (2.4.0) 
Using rspec-expectations (2.4.0) 
Using rspec-mocks (2.4.0) 
Using rspec (2.4.0) 
Using rspec-rails (2.4.1) 
Using webrat (0.7.3) 

Upvotes: 1

Views: 861

Answers (2)

traday
traday

Reputation: 1151

You need to change your line:

 p.username { "p#{first_name}_#{last_name}" }

to

p.username {|x| "#{x.first_name}_#{x.last_name}" }

That worked for me.

Upvotes: 1

Heikki
Heikki

Reputation: 15417

Do you have a Person class? Looks like it should be User instead:

Factory.define :person, :class => User do |p|

Documentation for dependent attributes:

Upvotes: 1

Related Questions