刚开始学习Ruby和Rails,现在我创建了一个控制器来验证用户身份并提供令牌。它完美地进行猴子测试(点击周围和邮递员),但在使用此命令进行测试时:
rails test
甚至这个测试都会失败:
require 'test_helper'
class UserControllerTest < ActionDispatch::IntegrationTest
test "should be true" do
assert true
end
end
它会在终端输出:
Error:
UserControllerTest#test_should_be_true:
ActiveRecord::StatementInvalid: SQLite3::ConstraintException: NOT
NULL constraint failed: users.email: INSERT INTO "users" ("created_at",
"updated_at", "id") VALUES ('2017-03-18 11:11:35.973444', '2017-03-18 11:11:35.973444', 980190962)
看不出应该是什么问题。因为如果我尝试在ActiveSupport中创建单元测试:TestCase将以相同的输出失败。
有谁能告诉我它为什么会这样做?
观测值! 如果您需要有关用户控制器的更多信息,请发表评论。感谢。
修改
在我的applicationcontroller中有这段代码:
class ApplicationController < ActionController::Base
require 'json_web_token'
protect_from_forgery with: :exception
protected
def authenticate_request!
if !payload || !JsonWebToken.valid_payload(payload.first)
return invalid_authentication
end
load_current_user!
invalid_authentication unless @current_user
end
def invalid_authentication
render json: { error: 'Invalid Request'}, status: :unauthorized
end
private
def payload
auth_header = request.headers['Authorization']
token = auth_header.split(' ').last
JsonWebToken.decode(token)
rescue
nil
end
def load_current_user!
@current_user = User.find_by(id: payload[0]['user_id'])
end
end
我在config / environments / test.rb下的测试设置
Rails.application.configure do
config.cache_classes = true
config.eager_load = false
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=3600'
}
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_dispatch.show_exceptions = false
config.action_controller.allow_forgery_protection = false
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :test
config.active_support.deprecation = :stderr
config.action_controller.allow_forgery_protection = false
end
答案 0 :(得分:0)
问题可能出在test/fixtures/users.yml
。有两个没有属性的用户:
one: {}
# column: value
#
two: {}
# column: value
当minitest启动时,它会尝试使用空字段创建两个用户,并且违反email
的非空约束。尝试删除这些行或使用正确的值填充它们