[rspec-users] Trouble testing a method with loop

David Currin dave at 2young2die.com
Mon Feb 4 06:24:46 EST 2008


I'm having trouble working out how to test a method that contains a
loop. I'm new to rspec so not sure what the best way is to tackle
this.

class Company < ActiveRecord::Base

def self.sync_with_basecamp
  companies = basecamp_fetch("companies")

  companies.each do |c|
    company = self.find_or_initialize_by_name_and_postcode(c.name, c.zip)
    company.county = c.state
    company.city = c.city
    company.save
  end

end

end

I started by checking that the number of companies in my mock
companies array was saved:

it "should write all records from array to the database" do
    lambda {
      Company.sync_with_basecamp
    }.should change(Company, :count).by(37)
  end

But I'm having trouble figuring out how to check individual records. I
can pull the first record from the mock array:

it "should populate name" do
    @company.first.name.should eql("The Media Collective")
end

But I can't check that this has been applied to the method because
rspec doesn't know about the save loop.

it "should populate name" do
    @company.name.should eql("The Media Collective")
end


Would appreciate some advice on how to tackle this please from someone
more familiar with rspec than me.


More information about the rspec-users mailing list