如何在工厂女孩中分配哈希?

时间:2015-09-08 14:01:52

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

我的模型有一个名为JSONB的字段。在postgres中category_paths

当我从factory_girl设置String时,factory_girl正在将值类型更改为Hash。考虑以下代码,即使我分配了String,它也会更改为FactoryGirl.define do factory :product do title "MyString" after(:build) do |p| p.category_paths = Hash.new puts p.category_paths.class # This prints as String end end end

class Product < ActiveRecord::Base
    acts_as_copy_target
    searchkick autocomplete: ['brand'], callbacks: :async
    scope :search_import, -> { includes(:product_offers) }
    has_many :product_offers, autosave: true
    validates :title, presence: true
    validate :validate_category_paths
end

这很奇怪,我无法弄清楚发生了什么。从Rails控制台尝试时,这很好用。只有在工厂使用时才会出现问题。这是factory_girl的工作原理吗?或者有办法控制这种行为吗?

这是产品型号

class B {

void SomeMethod(){

    A.StaticMethod();
}

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:10)

我在本地尝试了这个,它似乎适用于jsonb字段:

FactoryGirl.define do
  factory :product do
    title "MyString"
    category_paths { { some_key: some_value } }
  end
end

希望有所帮助!

答案 1 :(得分:1)

这对我有用

FactoryGirl.define do
  factory(:agent) do
    mls_data({
      :summary => {
        :first => 'Jane',
        :last => 'Doe',
      }
    })
  end
end

答案 2 :(得分:1)

如果你想在没有块的情况下执行哈希,你只需要使用括号。

所以它是这样的:

FactoryGirl.define do
  factory :product do
    title "MyString"
    category_paths({ some_key: some_value })
  end
end

但你也可以删除{}这样的哈希算法:

FactoryGirl.define do
  factory :product do
    title "MyString"
    category_paths(some_key: some_value)
  end
end

请注意,在将来的版本中,文字不会受到支持,因此您必须使用:

FactoryBot.define do
  factory :product do
    title { "MyString" }
    category_paths { { some_key: some_value } }
  end
end