我正在运行rails 3.0.3,并使用带有postgresql数据库的rspec-rails 2.4.1。每当我运行我的RSpec测试时,数据仍然在最后。有谁知道如何让rails或rspec在每次使用之间擦除测试环境的数据?rails测试数据库不会擦除
请告诉我,如果有任何进一步的信息可以使我的问题更容易回答。
谢谢!
Tristan
我正在运行rails 3.0.3,并使用带有postgresql数据库的rspec-rails 2.4.1。每当我运行我的RSpec测试时,数据仍然在最后。有谁知道如何让rails或rspec在每次使用之间擦除测试环境的数据?rails测试数据库不会擦除
请告诉我,如果有任何进一步的信息可以使我的问题更容易回答。
谢谢!
Tristan
安装database_cleaner gem,然后将其添加到您的spec_helper.rb。每次测试运行
RSpec.configure do |config|
config.use_transactional_examples = true
end
嘿谢谢鲍比。默认情况下,每次运行rspec时测试数据库不应该是空的? – WoodenKitty 2011-02-02 02:42:43
使用事务的例子来回滚数据,我只是把我自己通过,使用了错误before
块。
我意外地设置before
块作为all
代替each
:
before :all do
user = FactoryGirl.create(:user)
sign_in user
end
这导致user
留下来在数据库中为整个rspec
运行,这引起验证碰撞。
相反,before
应该是一个each
让一切都通过rspec
运行保持清洁:
before :each do
user = FactoryGirl.create(:user)
sign_in user
end
如果你犯了这个错误,那么你可能需要手动清理你的测试数据库在事情恢复正常之前。最简单的方法是截断每个表(除了schema_migrations
)。
另一种可能性后
Spec::Runner.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
您不需要任何额外的宝石来清理运行之间的测试数据库。在你的spec_helper.rb文件中,按如下方式配置rspec:
RSpec.configure do |c|
c.around(:each) do |example|
ActiveRecord::Base.connection.transaction do
example.run
raise ActiveRecord::Rollback
end
end
end
我相信在你运行测试之前数据已经被清除了,而不是之后。 – cam 2011-02-01 23:10:08
嘿凸轮。对不起,这可能是正确的,但现在都没有发生。 – WoodenKitty 2011-02-03 05:17:42