How to assign a hash in factory girl?
Asked Answered
F

3

10

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

Fray answered 8/9, 2015 at 14:1 Comment(3)
Show your product modelBerey
@SergioTulentsev Included product modelFray
How about the relevant section of schema.rb, which shows the table structure?Deryl
C
12

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!

Coverley answered 8/9, 2015 at 21:53 Comment(0)
H
1

This worked for me

FactoryGirl.define do
  factory(:agent) do
    mls_data({
      :summary => {
        :first => 'Jane',
        :last => 'Doe',
      }
    })
  end
end
Hamner answered 21/4, 2016 at 15:53 Comment(0)
L
1

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
Letterhead answered 30/10, 2017 at 17:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.