开发者

rspec validates_presence_of polymorphic attributes ruby on rails

I am writing an rspec for an address model that has a polymorphic attribute called :addressable. I am using factory girl for testing.

This model has no controller because I do not wish to create a standalone address but that 开发者_如何学运维doesnt stop the rspec from creating a standalone address. My model, factory and rspec are

class Address < ActiveRecord::Base
  belongs_to :addressable, :polymorphic => true
  belongs_to :state

  attr_accessible :street, :city, :state_id, :zip

  validates_presence_of :street, :city, :zip, :state 

  validates_associated :state
end

Factory.define :address do |address|
  address.street "1234 Any st"
  address.city "Any City"
  address.zip "90001"
  address.association :state  
end

describe Address do
  before(:each) do
  state = Factory(:state)
    @attr = {:street => "1234 Any St", :city => "Any City", :zip => "Any Zip", :state_id => state.id}
  end  

  it "should create a new address given valid attributes" do
    Address.create!(@attr).valid?.should be_true
  end
end

This rspec test will create an address with addressable_id and addressable_type of NULL and NULL but if I create from any other model, lets say a users model or a store model it will put in the correct data. So what I'm trying to figure out and research, unsuccessfully, is how do you validate_presence_of a polymorphic attribute and test it through a factory.

Sorry for being long winded but I havent been able to find a solution for this in the last couple of hours and I'm starting to consider I might be approaching this the wrong way.


I don't see anything in your spec that associates the address with an addressable. You are creating an address, but it's just out in space -- what is it connected to? NULL for addressable_id and addressable_type seems correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜