views:

136

answers:

1

I have this Factory:

Factory.define :email_address do |e|
  e.sequence(:address) { |n| "factory_#{n}@example.com" }
  e.validated true
end

When I run my specs with rake spec, it works fine.

When I run autospec, it fails right away, claiming that the email address is being used twice in two different objects (there is a validation which restricts this).

Why is it behaving differently under autospec?

Thanks, John

+1  A: 

I suspect what is happening is that FactoryGirl is resetting that n on each invocation from autospec, but the database hasn't been emptied.

First, to check this diagnosis, change your factory to the following:

Factory.define :email_address do |e|
  e.sequence(:address) { |n| puts "Email ##{n}"; "factory_#{n}@example.com" }
  e.validated true
end

If my diagnosis is correct, there are two possible fixes:

  1. change FactoryGirl to start from an index greater than the maximum ID used. This would involve some serious hacking on Factory::Sequence - you would probably have to turn Factory::Sequence.sequences from a Hash[Symbol => Proc] to a Hash[Symbol => [Proc, Integer] that remembered the highest index it used. Indeed, that might not even work since autospec does seem to be unloading the FactoryGirl classes properly (otherwise the sequence lookup wouldn't be failing and creating a new Factory::Sequence object).
  2. figure out why your database isn't being cleared between each autospec run. Have you checked your teardown methods? Does your testing database support transactions?
James A. Rosen
It has since started working again. Since I wrote the question I've upgraded a bunch of gems and my codebase has changed a lot. I really couldn't even guess what the problem was.Thanks for your input! If I have similar problems in the future I'll have a troubleshooting starting point.PeaceJohn
John