Rails MiniTest,为什么这个过程不是成功而是错误?
Rails MiniTest, Why doesn't this process as a success instead of an error?
[woo:~/Development … e-roles/test] master(+7/-3) 23s ± rails test
Running via Spring preloader in process 18905
Run options: --seed 34925
# Running:
E
Error:
UserTest#test_User_must_have_an_email_address:
ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2019-05-16 23:08:53.696224', '2019-05-16 23:08:53.696224', 298486374)
bin/rails test test/models/user_test.rb:4
Finished in 0.019202s, 52.0779 runs/s, 0.0000 assertions/s.
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
现在,user_test.rb
[woo:~/Development … e-roles/test] master(+7/-3) 1 ± cat models/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "User must have an email address" do
user = User.new
assert_raise SQLite3::ConstraintException do
user.save
end
end
end
我认为这会成功,因为我断言它会引发 SQLite3::ConstraintException,它确实如此。如果引发适当的异常,我希望测试成功。我做错了什么?
我认为要通过此测试,您需要断言 Ruby 异常,而不是 SQLite3 异常。您的 ActiveRecord 模型(我猜)是定义约束的地方。
像这样:
assert_raise ActiveRecord::RecordNotUnique do
user.save
end
断言 Ruby 异常将使该测试通过,即使您将来切换到不同的数据库,这是使用 ORM 的主要原因之一。
[woo:~/Development … e-roles/test] master(+7/-3) 23s ± rails test
Running via Spring preloader in process 18905
Run options: --seed 34925
# Running:
E
Error:
UserTest#test_User_must_have_an_email_address:
ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2019-05-16 23:08:53.696224', '2019-05-16 23:08:53.696224', 298486374)
bin/rails test test/models/user_test.rb:4
Finished in 0.019202s, 52.0779 runs/s, 0.0000 assertions/s.
1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
现在,user_test.rb
[woo:~/Development … e-roles/test] master(+7/-3) 1 ± cat models/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
test "User must have an email address" do
user = User.new
assert_raise SQLite3::ConstraintException do
user.save
end
end
end
我认为这会成功,因为我断言它会引发 SQLite3::ConstraintException,它确实如此。如果引发适当的异常,我希望测试成功。我做错了什么?
我认为要通过此测试,您需要断言 Ruby 异常,而不是 SQLite3 异常。您的 ActiveRecord 模型(我猜)是定义约束的地方。
像这样:
assert_raise ActiveRecord::RecordNotUnique do
user.save
end
断言 Ruby 异常将使该测试通过,即使您将来切换到不同的数据库,这是使用 ORM 的主要原因之一。