【问题标题】:Minitest gives different results on two consecutive runsMinitest 在两次连续运行中给出不同的结果
【发布时间】:2012-06-02 18:25:16
【问题描述】:

我一直在玩 Minitest,发现了一些我似乎无法解释的行为

我有一个非常简单的模型测试文件如下:

require 'minitest_helper'

describe User do

  before do
    @user = User.new(name: "Example User", email: "user@example.com",
                     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

当我在 'rake db:test:prepare' 之后第一次运行此代码时,测试通过了

当我连续第二次运行它时,它给了我一个错误:

test_0001_anonymous 0:00:00.132
错误 SQLite3::ConstraintException:列电子邮件不是唯一的: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

我似乎无法理解这是一个错误还是(更有可能)我遗漏了一些东西。 有没有比我知识渊博的人解释一下?

【问题讨论】:

    标签: ruby-on-rails ruby testing minitest


    【解决方案1】:

    toggle! 方法保存记录。因此,当您第二次运行测试时,数据库中已经有一条电子邮件为“user@example.com”的记录。并且保证电子邮件地址唯一性的验证失败。

    尝试改用toggle(无爆炸)。

    【讨论】:

    • 太好了,谢谢。除了每次调用 rake db:test:prepare 之外,您是否碰巧知道在使用 Minitest 运行测试之前确保干净的数据库/会话的好方法?我觉得这不是 rspec 的问题..
    【解决方案2】:

    您需要将每个测试包装在事务中(并将其回滚以便永远不会保存更改)或清除测试之间的所有表。如果不是从数据库中留下的垃圾会干扰后续的测试运行

    database_cleaner gem 是执行此操作的一种方式,它支持一系列 ORM 的多种策略(事务、截断等)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 2018-05-02
      • 2012-08-21
      • 2017-11-24
      相关资源
      最近更新 更多