Topic: Rspec and ActiveRecord with a serialized field

Hello all, has anyone else run into this?

I have an Order model with a product_data field that is serialized.

class Order < ActiveRecord::Base
  has_one :address, :as => :addressable, :dependent => :destroy
  belongs_to :user
  belongs_to :leaflet
  accepts_nested_attributes_for :address
  serialize :product_data

  validates_presence_of :copies, :user_id, :leaflet_id
end

And the following Factory_girl factory

Factory.define(:order) do |o|
  o.copies Conf.minimum_copies + 1
  o.approved '1'
  o.user_id 1
  o.leaflet_id 1
  o.product_data({'logo' => 'http://example.com/test.jpg', 'product' => 100})
end

If I use this factory in the following rspec test.

require 'spec_helper'

describe Order do

  before(:each) do
    @order = Factory(:order)
    @order.should be_valid
  end

  [:copies, :user_id, :leaflet_id].each do |field|
    it "should validate presence of #{field}" do
      @order[field] = nil
      @order.should_not be_valid
      @order.should have(1).error_on(field)
    end
  end

end

Then I get the following errors.

NoMethodError in 'Order should validate presence of copies'
undefined method `product_data=' for #<Order:0xb58d0058>

The Order code works fine in the actual site (I can do @order.product_data = params[:data] in the controller for example), just fails in these tests. It also fails if I try setting the product_data field in the before(:each) block instead.

Am I doing something wrong or is there some gotcha with regards to testing serialized fields with rspec? (Probably the former)

Last edited by RurouniJones (2010-06-22 23:01:12)