factory_girl工厂内的引用无法正常工作

时间:2011-01-21 09:48:55

标签: ruby-on-rails-3 factory-bot

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

给出了这个错误:

  

未定义的局部变量或方法   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 每个”   ./features/step_definitions/generic_steps.rb:2:in   /^these (.+) records$/' features/transaction_import.feature:7:in 鉴于这些人的记录'

这是我的配置(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) 

2 个答案:

答案 0 :(得分:1)

你有Person班吗?看起来应该是User而不是:

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

依赖属性的文档:

答案 1 :(得分:1)

您需要更改行:

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

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

这对我有用。