鉴于我有以下课程
class listing > ActiveRecord::Base
attr_accessible :address
belongs_to :owner
validates :owner_id, presence: true
validates :address, presence: true
end
在我/spec/models/listing_spec.rb
的测试中保存列表之前,有没有办法让我无法与所有者保持关联,而无需通过批量分配来访问owner_id
?
describe Listing do
before(:each) do
@owner = Factory :owner
@valid_attr = {
address: 'An address',
}
end
it "should create a new instance given valid attributes" do
listing = Listing.new @valid_attr
listing.owner = @owner
listing.save!
end
it "should require an address" do
listing = Listing.new @valid_attr.merge(:address => "")
listing.owner = @owner
listing.should_not be_valid
end
end
答案 0 :(得分:1)
不需要使用工厂女孩(除非你想......):
let(:valid_attributes) { address: 'An Address', owner_id: 5}
it "creates a new instance with valid attributes" do
listing = Listing.new(valid_attributes)
listing.should be_valid
end
it "requires an address" do
listing = Listing.new(valid_attributes.except(:address))
listing.should_not be_valid
listing.errors(:address).should include("must be present")
end
it "requires an owner_id" do
listing = Listing.new(valid_attributes.except(:owner_id))
listing.should_not be_valid
listing.errors(:owner_id).should include("must be present")
end
答案 1 :(得分:0)
如果您使用factory-girl
# it's probably not a good idea to use FG in the first one
it "should create a new instance given valid attributes" do
listing = Listing.new @valid_attr
listing.owner = @owner
listing.property_type = Factory(:property_type)
listing.save!
end
it "should require an address" do
# But here you can use it fine
listing = Factory.build :listing, address: ''
listing.should_not be_valid
end
it "should require a reasonable short address" do
listing = Factory.build :listing, address: 'a'*245
listing.should_not be_valid
end
答案 2 :(得分:0)
我不想在这里成为异议的代言人,但你不应该在验证规范中调用save!
或valid?
。 10次中有9次,如果你需要使用工厂女孩来检查你的模型的有效性,那就是非常错误的。你应该做的是检查每个属性的错误。
编写上述内容的更好方法是:
describe Listing do
describe "when first created" do
it { should have(1).error_on(:address) }
it { should have(1).error_on(:owner_id) }
end
end
此外,您可能不希望检查地址的状态,您要检查它是否为空,而不是空字符串,并且它不再是超过一定的长度。您需要使用validates_length_of
。