Search code examples
ruby-on-railsruby-on-rails-3rspecrspec2rspec-rails

Is there a way to prevent having to specify associations in tests?


Given I have the following class

class listing > ActiveRecord::Base
  attr_accessible :address
  belongs_to :owner

  validates :owner_id, presence: true
  validates :address, presence: true
end

Is there a way I can get away with not having to keep associating an owner before I save a listing in my tests in /spec/models/listing_spec.rb, without making owner_id accessible through mass assignment?

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

Solution

  • There is if you use 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