2011-07-07 67 views
1

鉴于我有下面的类有没有办法阻止在测试中指定关联?

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

有,如果你使用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 
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 
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

相关问题