Shorthand factory_girl 特征的块语法

Shorthand block syntax for factory_girl traits

是否可以对 factory_girl 特征使用 shorthand 块语法?

考虑这个工厂:

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

并且使用这个工厂有效:

create(:foo, traits: [:my_name])

但是我想对我的特征使用 shorthand 块语法,如下所示:

FactoryGirl.define do
  factory :foo do
    name "name"

    # using shorthand block syntax but does not work
    trait :my_name {name "Neil"}

  end
end

现在使用这个工厂出错了。这是发生的事情:

create(:foo, traits: [:my_name])

syntax error, unexpected '{', expecting keyword_end (SyntaxError)

这看起来很奇怪,因为我认为无论你在哪里使用 do ... end 你都可以选择 shorthand {} 块语法。

问题:我的 shorthand 块语法是否有问题 factory_girl trait 方法,这就是它出错的原因出去?或者:您只是不允许将 shorthand 块语法与 factory_girl traits 一起使用吗?有没有办法让 shorthand 块语法用于 factory_girl 特征?

Docs on the factory_girl trait attribute

你看,trait实际上是一个方法,它接受特征的名称和一个块。这些是方法的 2 个参数。当您使用 do ... end 语法时,Ruby 解释器可能会猜测您正在提供第二个(块)参数。但是,在第二种 { ... } 情况下,它并不清楚,因为你可能传递了一个 Hash 例如。

这就是为什么你需要明确你传递的第二个参数是这样的一个块:

trait(:my_name) { name "Neil" }