How to assign a hash in a factory girl?

I have a model that has a field called category_paths. This is JSONBin postgres.

When I set category_pathsfrom factory_girl, factory_girl changes the value type to String. Consider the following code, although I assign it Hash, it gets the value 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

This is strange, and I can’t understand what is happening. This works great when trying from the Rails console. The problem only occurs when used in a factory. So does factory_girl work? Or is there a way to control this behavior?

Here is the product model

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

Any help would be appreciated

+4
source share
3 answers

, , jsonb-:

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

, !

+9

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

If you want to execute a hash without a block, you just need to use parentheses.

So it will be like this:

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

But you can also drop {}for hash arguments like this:

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

Source: https://habr.com/ru/post/1606423/


All Articles