我有这段代码:
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"}
谢谢!
答案 0 :(得分:16)
我不确定是否还有其他办法。但这是一种做法
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了解更多信息
答案 1 :(得分: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" }