tags:

views:

23

answers:

1

Right now I have a model function that is something like this:

Class Address
  def first_line
    "#{self.building_name} #{self.street_name} #{self.suburb}".squeeze(" ").strip
  end
end

My address factory is define like this:

Factory.define :address do |f|
  f.building_name "Alpha"
  f.street_name "Bravo St"
  f.suburb "Charlie"
end

There are basically two ways to write the spec, first one is:

before(:each) do
  @address = Factory.build(:address)
end

@address.first_line.should == @address.building_name + " " +
                              @address.street_name + " " + 
                              @address.suburb

And other way is

@address.first_line.should == "Alpha Bravo St Charlie"

Which way do you think is better? And what is the reason for supporting one against the other?

+1  A: 

Neither. The first is a bit verbose and also feels a bit too pally with the implementation of the method. The second tightly couples your specs to your factories and will be a massive pain when you need to change the Factory.

Instead, use the short second style, but make the data used explicit in the spec:

@address = Factory.build(:address, :building_name => "Alpha",
                                   :street_name => "Bravo St.",
                                   :suburb => "Charlie")

@address.first_line.should == "Alpha Bravo St. Charlie"

This is also good because you can provide different test data to the method, which is necessary to test some of its other features:

@address = Factory.build(:address, :building_name => "Alpha    ",
                                   :street_name => "   Bravo St. ",
                                   :suburb => "   Charlie   " )

@address.first_line.should == "Alpha Bravo St. Charlie"
Daniel Lucraft