A way to define a simple model method

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

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

      

My factory address is defined like this:

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

      

Basically there are two ways to write a BOM, the first being:

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

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

      

And another 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 source to share


1 answer


Neither. The first one is a bit verbose, and it also feels too much too much with method implementation. The second one tightly connects your specs to your factories and will be a great pain when you need to change a Factory.

Use a short second style instead, but make the data used explicitly in the spec:

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

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

      



It's also good, because you can provide various test data to a method that needs to test some of its other functionality:

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

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

      

+1


a source







All Articles