ruby on rails——有没有办法避免在测试中指定关联?



假设我有以下类

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

不需要使用factory-girl(除非你想…):

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

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

我讨厌在这里发表异议,但你不应该在你的验证规范中调用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

同样,您可能不想检查地址的是否存在,您想检查它不是nil,不是空字符串,并且它不超过一定长度。您需要使用validates_length_of

相关内容

  • 没有找到相关文章

最新更新