简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM