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
4

3 回答 3

1

无需使用 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
于 2012-11-19T21:54:15.170 回答
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
于 2011-07-14T14:56:51.173 回答
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它。

于 2013-05-21T23:46:36.070 回答