使用 FactoryGirl 为属性添加别名的正确方法是什么?

发布于 2024-12-01 15:10:02 字数 499 浏览 1 评论 0原文

好吧,我在 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 吗?

Well, I have the following in factories.rb

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

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

And then when I create the user I do the following:

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

But it throws me an error of:

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

Shouldn't FactoryGirl convert the new_pass_ to new_pass_confirmation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

给妤﹃绝世温柔 2024-12-08 15:10:02

Factory_girl 中的别名用于防止两个属性相互冲突。经典的例子是关联与外键:如果您的工厂定义了“用户”关联,并且您通过传递“user_id”覆盖它,则“user_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

Aliases in factory_girl are used to prevent two attributes from clashing with each other. The classic example is an association vs a foreign key: if your factory defines a "user" association and you override it by passing "user_id," the "user_id" should take precedence.

If you wanted the password confirmation to override password, you'd use this alias:

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

It sounds like you want the password confirmation to default to the password, which you can do like this:

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

In the new syntax, you can leave out the block arguments:

FactoryGirl.define do
  factory :user do
    new_pass  'asdasdasd'
    new_pass_confirmation { new_pass }
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文