Reputation: 5178
Is it possible to use the shorthand block syntax for factory_girl traits?
Consider this factory:
FactoryGirl.define do
factory :foo do
name "name"
# not using the block shorthand {} syntax, instead using do...end block syntax
trait :my_name do
name "Neil"
end
end
end
And using this factory works:
create(:foo, traits: [:my_name])
However I would like to use the shorthand block syntax for my traits like so:
FactoryGirl.define do
factory :foo do
name "name"
# using shorthand block syntax but does not work
trait :my_name {name "Neil"}
end
end
And now using this factory errors out. Here is what happens:
create(:foo, traits: [:my_name])
syntax error, unexpected '{', expecting keyword_end (SyntaxError)
This seems odd because I thought that wherever you use do ... end
you can opt for the shorthand {}
block syntax.
Question: Is there something wrong with my shorthand block syntax for the factory_girl trait
method and that is why it is erroring out? Or: are you just not allowed to use the shorthand block syntax with factory_girl traits
? Is there a way to make using the shorthand block syntax for factory_girl traits work?
Docs on the factory_girl trait attribute
Upvotes: 0
Views: 448
Reputation: 11813
You see, trait
is actually a method that takes a name of the trait and a block. These are 2 parameters of a method. When you used do ... end
syntax, Ruby interpreter could guess that you are giving a second (block) argument. But, in the second { ... }
case, it is not clear, because you might be passing a Hash
for example.
That's why you need to make it clear that you are passing in the second param and it is a block like this:
trait(:my_name) { name "Neil" }
Upvotes: 2