use*_*728 4 ruby testing ruby-on-rails factory-bot
我有这个代码:
FactoryGirl.define do
factory :gimme_a_hash, class: Hash do
one 'the number 1'
two 'the number 2'
end
end
Run Code Online (Sandbox Code Playgroud)
它返回一个如下的哈希:
1.9.3p448 :003 > FactoryGirl.build : gimme_a_hash
=> {:one=>"the number 1", :two=>"the number 2"}
Run Code Online (Sandbox Code Playgroud)
如何创建一个工厂,将带有字符串化数字的哈希作为键返回?
理想情况下,我想返回以下哈希:
=> { "1"=>"the number 1", "2"=>"the number 2"}
Run Code Online (Sandbox Code Playgroud)
谢谢!
ush*_*sha 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
Run Code Online (Sandbox Code Playgroud)
结果:
1.9.3p194 :001 > FactoryGirl.build(:gimme_a_hash)
=> {"1"=>"the number 1", "2"=>"the number 2"}
Run Code Online (Sandbox Code Playgroud)
更新
默认情况下,factory_girl初始化给定类的对象,然后调用setter来设置值.在这种情况下,a=Hash.new然后a.1 = 'the_number_1'哪个不会起作用
通过说initialize_with {attributes},我要求它做Hash.new({"1" => "the number 1", "2" => "the number 2"})
阅读文档以获取更多信息
| 归档时间: |
|
| 查看次数: |
4902 次 |
| 最近记录: |