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?
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