我正在为一个地址模型编写一个 rspec,该地址模型具有一个名为:addressable
. 我正在使用工厂女孩进行测试。
该模型没有控制器,因为我不希望创建独立地址,但这不会阻止 rspec 创建独立地址。我的模型、工厂和 rspec 是
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
此 rspec 测试将创建一个 addressable_id 和 addressable_type 为 NULL 和 NULL 的地址,但如果我从任何其他模型创建,比如说用户模型或商店模型,它将放入正确的数据。因此,我试图弄清楚和研究的是如何验证多态属性并通过工厂对其进行测试,但没有成功。
很抱歉啰嗦了,但在过去的几个小时里我还没有找到解决方案,我开始考虑我可能以错误的方式处理这个问题。