【问题标题】:Referencing a field in a Fabrication引用 Fabrication 中的字段
【发布时间】:2015-03-01 18:12:08
【问题描述】:

在下面的示例中,我希望 abbr 只是 name 的前 3 个字母,但我得到一个 >> 未定义的局部变量 name... 我猜是因为 name 超出了范围{} 块?

Fabricator(:team) do
  name { Faker::Name.first_name }
  abbr { Faker::Name.first_name[0..2] }
  league { Fabricate(:league) }  
end

我怎样才能使abbr 只是name 的前三个字母?

即这会引发错误

Fabricator(:team) do
  name { Faker::Name.first_name }
  abbr { name[0..2] }  \\ error name is undefined here
  league { Fabricate(:league) }  
end

【问题讨论】:

  • 只需从您的 rails 控制台显示Team.column_names 的输出。只是为了确保您的 Team 模型中是否有 name 属性。
  • 或者显示完整的错误堆栈
  • 您的编辑现在有意义了,
  • 试试abbr { Fabricate.attributes_for(:team)[:name][0..2] },让我知道它是否适合你..
  • 失败/错误:无法从回溯 SystemStackError 中找到匹配行:堆栈级别太深

标签: ruby rspec fabrication-gem


【解决方案1】:

您也可以通过接受 abbr 值块中的属性散列来做到这一点。

Fabricator(:team) do
  name { Faker::Name.first_name }
  abbr { |attrs| attrs[:name][0..2] }
  league
end

不相关,但如果你这样写,联赛会自动扩展到你上面指定的内容。

【讨论】:

    【解决方案2】:

    你应该可以做一个 before_save 回调...

    Fabricator(:team) do
      before_save {|team| team.abbr ||= team.name[0..2] }
      name { Faker::Name.first_name }
      league { Fabricate(:league) }  
    end
    

    如果通过了 abbr 的值,则编辑为可选。

    【讨论】:

    • 这是否会阻止我在制作时传递“缩写”?
    • 无论设置什么team.abbr ...如果我为“abbr”传递了一个值,它会在保存时被覆盖?
    • 是的,它会覆盖一个传递的变量,但你可以用team.abbr ||= team.name[0..2]修复它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    • 2011-02-27
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多