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

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

问题描述

我是 Rspec 和 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 个模型记录,我不想为了测试而删除它.里面有 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.

factory girl 是否提供从数据库中删除记录然后回滚此删除?类似于它如何在数据库中创建记录并回滚

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天全站免登陆