使用Rails 4.2.0.rc2,我在用户注册中添加了一个“接受服务条款”复选框
在我添加的用户模型中
attr_accessor :terms_of_service
validates_acceptance_of :terms_of_service, acceptance: true在视野中
<%= f.check_box :terms_of_service %>最后,在控制器中,我将它添加到参数列表中。
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation, :terms_of_service)
end这和预期的一样工作,但是由于我对实现进行了更改,所以我预计相关的测试将出现赤字。但是,这个测试通过了,我不明白为什么:
assert_difference 'User.count', 1 do
post users_path, user: { name: "Example User",
email: "user@example.com",
password: "password",
password_confirmation: "password" }
end我可以像这样重写我的测试
test "accept terms of service" do
get signup_path
assert_no_difference 'User.count' do
post users_path, user: { name: "Example User",
email: "user@example.com",
password: "password",
password_confirmation: "password",
terms_of_service: "0" }
end
assert_difference 'User.count', 1 do
post users_path, user: { name: "Example User",
email: "user@example.com",
password: "password",
password_confirmation: "password",
terms_of_service: "1" }
end
end但我很好奇最初的测试为什么失败了。我从这件事中得到的是validates_acceptance_of的零通行证。
这是有意的行为吗?
发布于 2016-07-09 13:16:47
简而言之,是的,nil是允许的。我以前也有过同样的问题。
主动模型/验证/可接受性
module ActiveModel
module Validations
class AcceptanceValidator < EachValidator # :nodoc:
def initialize(options)
super({ allow_nil: true, accept: "1" }.merge!(options))
setup!(options[:class])
end
# ...
end
# ...
end
# ...
end在初始化器中,它将allow_nil与选项合并,因此允许使用nil (或者缺少值,我应该说)。acceptance,但我错过了。
这在我的测试中也被我咬了几次--当我确定它们不应该通过的时候,我一直在获得通过验证。现在我们知道原因了!
https://stackoverflow.com/questions/28103235
复制相似问题