[rspec-users] pontential bug in rspec_on_rails and ActiveRecord transactions

Esad Hajdarevic esad at esse.at
Wed Apr 4 11:43:18 EDT 2007


Hello rspec-users,

I've encountered a strange bug in rspec, but it may be me who is wrong.

I'm running latest version from the trunk (r1678) of both rspec and 
rspec_on_rails.

Please consider the following model:

class Url < ActiveRecord::Base
   def after_save
     Contact.create!(:primary_email => 'user at example.com')
     raise ActiveRecord::RecordInvalid.new(self)
   end
end

Basically what it does is that in after_save it will insert a new 
contact into database but after the exception has been raised, the Rails 
will make a rollback on transaction.

Running in console:

Url.create!(:url => 'http://example.com')

Will yield following SQL (taken from the log)

  BEGIN
  INSERT INTO urls (`icon_url`, `domain`, `url`, `cached_version`, 
`description`, `created_at`) VALUES(NULL, NULL, 
'http://www.example.com/', 0, NULL, '2007-04-04 15:36:08')
  INSERT INTO contacts (`internal_id`, `name`, `updated_at`, 
`primary_email`, `notes`, `user_id`, `created_at`) VALUES(NULL, NULL, 
'2007-04-04 15:36:08', 'user at example.com', NULL, NULL, '2007-04-04 
15:36:08')
  ROLLBACK

However, when I wrote the specification that looked something like this:

context "Url" do
   setup do
     Contact.delete_all
     Url.delete_all
   end

   specify do
     lambda { Url.create(:url => 'http://www.example.com/') }.should 
raise_error
     Url.count.should == 0
     Contact.count.should == 0
   end
end

It failed!

The log output was:

  BEGIN
  DELETE FROM contacts
  DELETE FROM urls
  INSERT INTO urls (`icon_url`, `domain`, `url`, `cached_version`, 
`description`, `created_at`) VALUES(NULL, NULL, 
'http://www.example.com/', 0, NULL, '2007-04-04 15:35:46')
  INSERT INTO contacts (`internal_id`, `name`, `updated_at`, 
`primary_email`, `notes`, `user_id`, `created_at`) VALUES(NULL, NULL, 
'2007-04-04 15:35:46', 'user at example.com', NULL, NULL, '2007-04-04 
15:35:46')
  SELECT count(*) AS count_all FROM urls
  ROLLBACK

How did count statement got into transaction? Is rspec doing some magic 
with ActiveRecord that is causing this to happen?

Thanks for your help,

Esad



More information about the rspec-users mailing list