【问题标题】:Which is the correct method for aliasing attributes with FactoryGirl?使用 FactoryGirl 对属性进行别名处理的正确方法是什么?
【发布时间】:2011-08-26 00:37:24
【问题描述】:

好吧,我在 factory.rb 中有以下内容

Factory.alias /(.*_)confirmation/, "\1"

Factory.define :user do |f|
  f.new_pass  'asdasdasd'
  f.new_pass_confirmation 'asdasdasd'
end

然后,当我创建用户时,我会执行以下操作:

Factory.build(:user, :new_pass => 'something', :new_pass_ => 'something_else')

但它给我一个错误:

undefined method `new_pass_=` for #<User:0x1234567>

FactoryGirl 不应该将 new_pass_ 转换为 new_pass_confirmation 吗?

【问题讨论】:

    标签: ruby-on-rails testing rspec factory-bot


    【解决方案1】:

    factory_girl 中的别名用于防止两个属性相互冲突。经典示例是关联与外键:如果您的工厂定义了“用户”关联并且您通过传递“用户 ID”来覆盖它,则“用户 ID”应该优先。

    如果您希望密码确认覆盖密码,您可以使用此别名:

    Factory.alias /(.*)_confirmation/, "\1"
    

    听起来您希望密码确认默认为密码,您可以这样做:

    Factory.define :user do |f|
      f.new_pass  'asdasdasd'
      f.new_pass_confirmation { |u| u.new_pass }
    end
    

    在新语法中,您可以省略块参数:

    FactoryGirl.define do
      factory :user do
        new_pass  'asdasdasd'
        new_pass_confirmation { new_pass }
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 2012-03-31
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多