Ruby on rails Rails-在模型规范中设计测试认证
我觉得这应该是一个简单的问题,但我一直在努力寻找答案。我已经在我的Rails项目中设置了Desive for authentication,它工作得很好。我还自定义了密码验证和登录要求。具体来说,用户应该能够使用用户名或电子邮件登录,并且电子邮件不应区分大小写 如何在我的模型规格中对此进行测试?具体测试:Ruby on rails Rails-在模型规范中设计测试认证,ruby-on-rails,ruby-on-rails-3,authentication,devise,Ruby On Rails,Ruby On Rails 3,Authentication,Devise,我觉得这应该是一个简单的问题,但我一直在努力寻找答案。我已经在我的Rails项目中设置了Desive for authentication,它工作得很好。我还自定义了密码验证和登录要求。具体来说,用户应该能够使用用户名或电子邮件登录,并且电子邮件不应区分大小写 如何在我的模型规格中对此进行测试?具体测试: 使用电子邮件登录(全部较低),密码有效 使用电子邮件登录(全部为大写),密码有效 使用用户名和密码登录是有效的 使用用户名(大小写混乱)和密码登录无效 基本上,我只需要一个函数,它接收登录详细
我经常发现的唯一设计测试是在控制器中,它没有帮助,因为它只是自动登录用户,而不需要登录详细信息。这里有两个不同的组件: 1) 查找用户
2) 正在验证用户的密码 查找用户由
find\u for\u database\u authentication
()
密码验证由valid\u password?
方法()处理
因此,您希望将此测试分为:
context "finding a user" do
let(:user) { FactoryGirl.create(:user) }
it "can find by lower email" do
User.find_for_database_authentication( {login: user.email.downcase} ).should eq(user)
end
it "can find by upper email" do
User.find_for_database_authentication( {login: user.email.upcase} ).should eq(user)
end
it "can find by jumbled username" do
scrambled_username = user.username.downcase.chars.map{|c| rand() > 0.5 ? c.capitalize : c}.join
User.find_for_database_authentication( {login: username} ).should eq(user)
end
end
context "authenticating a user" do
let(:user) { FactoryGirl.create(:user, password: "password123", password_confirmation: "password123") }
it "will validate a correct password" do
user.valid_password?("password123").should be_true
end
it "will not validate an incorrect password" do
user.valid_password?("bad-password").should be_false
end
end
为什么你想测试一些设计本身应该已经测试过的东西?您是否有任何可能干扰的自定义代码?这正是我想测试它的原因。我喜欢使用其他gem,而不是自己重写东西,但它们的功能在未来的变化中(甚至现在)可能会崩溃的可能性不是零。我不认为冗余测试是一件坏事。我同意@ryanbigg的观点,即用户身份验证不是您应该测试的东西。但是如果您必须添加自定义代码以使find_for_数据库_身份验证工作,我认为测试工作正常。