Factory Girl with serialized field

2019-05-28 16:15发布

问题:

I'm having this issue with factory girl where it gives me a undefined method 'each' for #<String:0x0000012915bc18> error with a serialized field coming from the factory.

within ActiveRecord, it runs the each with no problem, as the object returned is an array.

My question is: how should I format the serialized object in my factory? The way that active record returns it? or the way it's actually stored in the database? (i.e. serialized or not?) will rspec do the same serialize magic on saving and retrieving that active record does?

this is a simplified version of what I'm doing:

Tvdb.rb-- Model

class Tvdb < ActiveRecord::Base

  set_table_name 'tvdb'
  serialize :cache

  def self.episodes(id)
    cached = self.find_by_term('episodes_' + id.to_s)
    return cached.cache unless cached.nil?

    info = self.series_info(id)
    request = info.episodes

    Tvdb.create(:term=>'episodes_' + info.id.to_s, :cache=>request)
    return request
  end
end

Then in my Series.rb model I can do this:

class Series < ActiveRecord::Base

  def episodes
    episodes = Tvdb.episodes(self.tvdb_id)
    episodes.each do |episode|
      puts episode.name
    end
  end

end

Tvdb.rb -- Factory

FactoryGirl.define do
  factory :series1_episodes, :class=>Tvdb do
    term 'episodes_79488'
    cache %q([#<AnObject::Module:0x000001290a4568 @value="dsada"]>,#<AnObject::Module:0x0002321290a4568 @value="dsadsada"]> )
  end  
end

note: The syntax of the cache value might be invalid here, I tried to shorten what was a very long serialized object. The point is that it works in my model, but not in rspec

and in my *series_spec.rb* calling this:

series.episodes.count.should_not == 0

gives that error

undefined method 'each' for #<String:0x0000012915bc18>

回答1:

In your factory, you shouldn't set cache to the serialized value, but to the actual value.

FactoryGirl.define do
  factory :series1_episodes, :class => Tvdb do
    term 'episodes_79488'
    cache ["foo", "bar"]
  end
end