How to use FactoryGirl to create an attribute called "alias"?
Asked Answered
O

2

23

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.

Orientalize answered 16/2, 2012 at 10:46 Comment(0)
K
36

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'

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

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

is the same as

FactoryGirl.define do
  factory :blah do
    name "some value"
  end
end
Knelt answered 16/2, 2012 at 10:51 Comment(2)
Using self.alias did the trick. I was positive I had already tried that though. (-: Thanks!Orientalize
Was just having this problem where my model has an attribute called "end". self.end makes it work.Neocene
P
2

Define a variable for the factory .. do block and call methods on it.

FactoryGirl.define do
  factory :blah do |f|
    f.name "dummy"
    f.alias "dummy"
  end
end
Propellant answered 2/10, 2017 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.