Rspec/FactoryGirl:清除数据库状态 [英] Rspec/FactoryGirl: clean database state

查看:66
本文介绍了Rspec/FactoryGirl:清除数据库状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Rspec和Factory girl的新手,希望我的测试在特定的数据库状态下运行.我知道我可以让Factory girl创建这些记录,并且在测试运行后这些对象将被销毁,但是如果我的数据库中有数据,会发生什么情况.

I am new to Rspec and Factory girl and would like my test to run on a specific database state. I understand I can get Factory girl to create these records, and the objects will be destroyed after the test run, but what happens if I have data in the database.

例如:当我通过Factory Girl创建的数据库中有3条记录时,我希望运行我的测试.但是,我目前在数据库中已经有1个模型记录,并且我不想为了测试而将其删除.那里只有那一个模型会毁了我的测试.

For example: I want my test to run when there are 3 records in the database that I created through Factory Girl. However, I currently already have 1 model record in the database, and I don't want to delete it just for the test. Having that 1 model in there ruins my test.

数据库内容

[#<Leaderboard id: 1, score: 500, name: "Trudy">]

leaderboard_spec.rb

require 'spec_helper'

describe Rom::Leaderboard do

    describe "poll leaderboard" do
        it "should say 'Successful Run' when it returns" do
            FactoryGirl.create(:leaderboard, score: 400, name: "Alice")
            FactoryGirl.create(:leaderboard, score: 300, name: "Bob")
            FactoryGirl.create(:leaderboard, score: 200, name: "John")
            Leaderboard.highest_scorer.name.should == "Alice"
        end
    end

end

现在,我的测试将失败,因为它会错误地认为Trudy是得分最高的人,因为该测试的运行状态不正确.

Now my test will fail because it will incorrectly assume that Trudy is the highest scorer, since the test have run in an incorrect state.

工厂女孩是否仍然提供从数据库中删除记录然后回滚此删除的功能?类似于它在数据库中创建记录并回滚的方式

Does factory girl offer anyway to delete records from the database then rollback this delete? Similar to how it creates records in the database and rollsback

推荐答案

使用database_cleaner gem很受欢迎.您可以在这里找到它:

Its popular to use the database_cleaner gem. You can find it here:

https://github.com/bmabey/database_cleaner

文档建议对rspec使用以下配置:

The documentation recommends the following configuration for 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

这将确保您每个测试都有一个干净的数据库.

This will you make sure you have a clean database for each test.

这篇关于Rspec/FactoryGirl:清除数据库状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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