mysql错误:不能销毁使用factoryGirl创建的对象 [英] mysql error: can't destroy an object that is created using factoryGirl

查看:138
本文介绍了mysql错误:不能销毁使用factoryGirl创建的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用mysql db在rails中运行rspec。在我使用factoryGirl创建一个对象后,我想破坏它,以便数据库看起来干净的下一个规格运行。
这是我在我的规范中设置的方式:

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

运行rspec时遇到错误:

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

我设置了 :dependent => :destroy 在用户模型中
这里有什么问题?

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

推荐答案

问题是,用@user类变量引用的对象是未初始化的常量。 IE,FactoryGirl工作正常,您的变量不能正确实例化@user对象。当连接不是数据库表字段时,你可能有一个连接的引用。

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.

如果是MySQL问题,会出现与ActiveRecord相关的错误信息。

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

如果要在测试之前/之后清理数据库,请尝试使用此gem。它工作伟大。
http://rubygems.org/gems/database_cleaner

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

以下是我在 rails项目中使用RSpec配置的方法

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

这篇关于mysql错误:不能销毁使用factoryGirl创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆