如何定义一个FactoryGirl工厂,返回一个带有字符串键的哈希表?

7

我有这段代码:

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"}

谢谢!
2个回答

19

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

  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"})

阅读文档以获取更多信息。


请问您能否解释一下initialize_with及其块的含义?我也很想了解您为什么决定使用f.send - user3084728
谢谢。如果您愿意看一下,我发布了一个带有不同要求集的后续问题。http://stackoverflow.com/questions/20645009/factorygirl-factory-with-traits-that-returns-a-hash-with-stringed-keys - user3084728

1
你正在寻找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意味着你有一个对象而不是一个数据结构。 - DickieBoy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接