gpt4 book ai didi

ruby-on-rails - 如何定义返回带字符串键的哈希的 Factory Girl 工厂?

转载 作者:数据小太阳 更新时间:2023-10-29 07:21:01 25 4
gpt4 key购买 nike

我有这个代码:

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

谢谢!

最佳答案

不知道有没有别的办法。但这是一种方法

  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了解更多信息

关于ruby-on-rails - 如何定义返回带字符串键的哈希的 Factory Girl 工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20621536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com