I’ve been playing around a bit with Minitest, and have found behavior that I can’t seem to find an explanation for
I have a very simple model test file as follows:
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
When I run this code for the first time after a ‘rake db:test:prepare’, the test passes
When I run it for the second consecutive time, it gives me an error:
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 (?, ?, ?, ?, ?, ?)
Yet this error does not seem to occur if I take out the
before { @user.toggle!(:admin) }
My minitest_helper.rb is as follows:
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
I can’t seem to understand if this is a bug or if (more likely) I’m missing something.
Could someone more knowledgeable than me please explain this?
toggle!method saves the record. So, when you run test for the second time, there are already one record with the email “user@example.com” in the database. And the validation which guarantees uniqueness of the email address fails.Try to use
toggle(without bang) instead.