Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a hash in factory girl?

I have a model which has a field called category_paths. It is JSONB in postgres.

When I set the category_paths from factory_girl, factory_girl is changing the value type to String. Consider the following code, even though I am assigning a Hash, it gets changed to 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 weird and I am not able to figure out what is happening. This works fine when tried from Rails console. The problem happens only when used in factory. Is this how factory_girl works? 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

like image 550
Navaneeth K N Avatar asked Sep 08 '15 14:09

Navaneeth K N


3 Answers

I tried this out locally and it appears to work with jsonb fields:

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

Hope that helps!

like image 152
madcow Avatar answered Nov 20 '22 16:11

madcow


If you want to execute the hash without a block, you simply have to use parenthesis.

So it'd be like this:

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

But you can also drop the {} for hash args like so:

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

As a note, in future releases, literals won't be supported, so you'll have to use:

FactoryBot.define do
  factory :product do
    title { "MyString" }
    category_paths { { some_key: some_value } }
  end
end
like image 32
grepsedawk Avatar answered Nov 20 '22 18:11

grepsedawk


This worked for me

FactoryGirl.define do
  factory(:agent) do
    mls_data({
      :summary => {
        :first => 'Jane',
        :last => 'Doe',
      }
    })
  end
end
like image 30
Jason Deppen Avatar answered Nov 20 '22 16:11

Jason Deppen