【问题标题】:How do I define a FactoryGirl factory that returns a Hash with stringed keys?如何定义返回带有字符串键的哈希的 Factory Girl 工厂?
【发布时间】:2013-12-16 21:44:01
【问题描述】:

我有这个代码:

FactoryGirl.define do
  factory :gimme_a_hash, class: Hash do
    one 'the number 1'
    two 'the number 2'
  end
end

它返回一个看起来像这样的哈希:

1.9.3p448 :003 > FactoryGirl.build : gimme_a_hash
 => {:one=>"the number 1", :two=>"the number 2"}

如何创建一个工厂以返回带有字符串化数字作为键的哈希?

理想情况下,我希望返回以下哈希:

 => { "1"=>"the number 1", "2"=>"the number 2"}

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby testing factory-bot


    【解决方案1】:

    我不确定是否还有其他方法。但这是一种方法

      factory :gimme_a_hash, class: Hash do |f|
        f.send(1.to_s, 'the number 1')
        f.send(2.to_s, 'the number 2')
    
        initialize_with {attributes.stringify_keys}
      end
    

    结果:

    1.9.3p194 :001 > FactoryGirl.build(:gimme_a_hash)
     => {"1"=>"the number 1", "2"=>"the number 2"}
    

    更新

    默认情况下,factory_girl 初始化给定类的对象,然后调用 setter 来设置值。在这种情况下,a=Hash.new 然后a.1 = 'the_number_1' 将不起作用

    initialize_with {attributes},我要求它做Hash.new({"1" => "the number 1", "2" => "the number 2"})

    阅读documentation了解更多信息

    【讨论】:

    • 您能解释一下initialize_with 它是块吗?我也很想了解您是如何做出使用f.send 的决定的。
    • 谢谢。如果您想看一下,我发布了一个带有不同要求的后续 Q。 stackoverflow.com/questions/20645009/…
    【解决方案2】:

    您正在寻找 attributes_for 方法。

    factory :user do
      age { Kernel.rand(50) + 18 }
      email 'fake@example.com'
    end
    
    FactoryGirl.attributes_for(:user)
    => { :age => 31, :email => "fake@example.com" }
    
    FactoryGirl.attributes_for(:user).stringify_keys
    => { "age" => 31, "email" => "fake@example.com" }
    

    【讨论】:

    • 我认为他不是在寻找attributes_forattributes_for 暗示你有一个对象而不是一个数据结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 2014-10-10
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多