2012-06-02 17 views
1

我一直在玩弄MINITEST了一下,發現行爲,我似乎無法找到MINITEST給出了兩個連續的運行

的解釋,我有一個非常簡單的模型測試文件不同的結果如下:

require 'minitest_helper' 

describe User do 

    before do 
    @user = User.new(name: "Example User", email: "[email protected]", 
        password: "foobards", password_confirmation: "foobards") 
    end 

    describe "with admin attribute set to 'true'" do 
    before { @user.toggle!(:admin) } 

    it { @user.admin.must_equal true } 
    end 
end 

當我一個後運行首次此代碼「耙分貝:測試:準備」,測試通過

當我運行它連續第二時間,它給我一個錯誤:

test_0001_anonymous 0:00:00.132
ERROR SQLite3::ConstraintException: column email is not unique: INSERT INTO "users" ("admin", "created_at", "email", "name", "password_digest", "updated_at") VALUES (?, ?, ?, ?, ?, ?)

似乎然而,這個錯誤不會,如果我拿出來發生

before { @user.toggle!(:admin) } 

我minitest_helper.rb如下:

ENV["RAILS_ENV"] = "test" 
require File.expand_path("../../config/environment", __FILE__) 
require "minitest/autorun" 
require "capybara/rails" 
require "active_support/testing/setup_and_teardown" 

class IntegrationTest < MiniTest::Spec 
    include Rails.application.routes.url_helpers 
    include Capybara::DSL 
    register_spec_type(/integration$/, self) 
end 

class HelperTest < MiniTest::Spec 
    include ActiveSupport::Testing::SetupAndTeardown 
    include ActionView::TestCase::Behavior 
    register_spec_type(/Helper$/, self) 
end 

Turn.config.format = :outline 

我似乎無法理解,如果這是一個錯誤或如果(更可能)我錯過了一些東西。 有人比我更懂事請解釋一下嗎?

回答

1

toggle!方法保存記錄。因此,當您第二次運行測試時,數據庫中已經有一條包含電子郵件「[email protected]」的記錄。並且確保電子郵件地址唯一性的驗證失敗。

嘗試使用toggle(沒有爆炸)。

+0

精彩的多策略(交易,截斷等),謝謝。除了調用rake數據庫之外,在使用Minitest運行測試之前,您碰巧知道確保清理數據庫/會話的一種好方法:test:prepare every time?我覺得這與rspec沒有太大關係。 – hangsu

1

您需要將每個測試包裝在一個事務中(並將其回滾,以便從未保存更改)或清除測試之間的所有表。如果不是垃圾從數據庫中留下將隨後干擾測試運行

的database_cleaner寶石是這樣的一種方式,並支持一系列的ORM