如何使用FactoryGirl创建名为"alias"的属性? [英] How to use FactoryGirl to create an attribute called "alias"?

查看:54
本文介绍了如何使用FactoryGirl创建名为"alias"的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否可以使用FactoryGirl创建一个称为别名"的属性,因为别名是Ruby中的保留字.

I'm just wondering whether it's possible to create an attribute called "alias" using FactoryGirl, since alias is a reserved word in Ruby.

FactoryGirl.define do
  factory :blah do
    name "dummy"
    alias "dummy"
  end
end

我尝试了各种转义操作的组合,但是无法获得有用的工作信息.

I've tried various combinations of escaping things but can't get anything useful to work.

推荐答案

Ruby不知道您是要尝试调用名为alias的方法还是将另一个方法作为别名,并且默认为后者.您可以这样做消除歧义

Ruby doesn't know whether you're trying to call a method called alias or alias one method as another, and defaults to the latter. You can disambiguate by doing

self.alias "dummy"

即,通过明确指定接收者.在其他情况下,无论您是调用方法还是执行其他操作(例如,

ie, by explicitly specifying the receiver. This is usually the way to go in other cases where it is ambiguous whether you are calling a method or doing something else e.g.

self.foo = 'bar'

调用foo=方法,而不是创建一个名为foo的局部变量.

to call the foo= method rather than create a local variable called foo.

对于字段名较少这是行不通的.工厂女孩的DSL使用method_missing,因此,如果DSL对象具有该名称的方法,则将改为调用该名称.在这种情况下,您可以执行DSL Sugar正常为您执行的操作,然后直接致电add_attribute:

For a small number of field names this won't work. Factory girl's DSL uses method_missing so if the DSL object has a method of that name it will be called instead. In those cases you can do what the DSL sugar normal does for you and call add_attribute directly:

FactoryGirl.define do
  factory :blah do
    add_attribute :name, "some value"
  end
end

FactoryGirl.define do
  factory :blah do
    name "some value"
  end
end

这篇关于如何使用FactoryGirl创建名为"alias"的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆