mysql error: can't destroy an object that is created using factoryGirl

冷暖自知 提交于 2019-12-11 06:54:20

问题


I was using mysql db to run rspec in rails. After I create an object using factoryGirl, I would like to destroy it so that the db looks clean for the next spec running. Here is how i set up in my spec:

before (:each) do
  User.destroy_all
  @user = Factory.create :user
end

after (:each) do
 @user.destroy
end

I got an error running rspec:

Failure/Error: @user.destroy_all
 NameError:
   uninitialized constant User::connection

Failure/Error: @user.destroy
 NameError:
   uninitialized constant User::connection

I do set up :dependent => :destroy in user model What is wrong here?


回答1:


The issue is that the Object referenced with the @user class variable is an "Uninitialized Constant". IE, FactoryGirl is working fine, your variables are not correctly instantiating the @user object. You probably have an reference to connection when connection is not a datbase table field.

If it was a MySQL issue, there would be error messages associated with ActiveRecord.

If you want to clean your database before/after tests, try using this gem. It works great. http://rubygems.org/gems/database_cleaner

Here's how I configured with RSpec in a rails project,

RSpec.configure do |config|        
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end
  config.before(:each) do
    DatabaseCleaner.start
  end
  config.after(:each) do
    DatabaseCleaner.clean
  end
end


来源:https://stackoverflow.com/questions/10199067/mysql-error-cant-destroy-an-object-that-is-created-using-factorygirl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!