使用 Rails 和 Devise 进行功能测试.在我的固定装置中放什么? [英] Functional testing with Rails and Devise. What to put in my fixtures?
问题描述
我想对使用 Devise 和 CanCan 的 Rails 3 应用进行一些功能测试.
Hi I'm wanting to do some functional testing of my Rails 3 app that uses Devise and CanCan.
在我的用户模型中,我有用户年龄,我想测试用户是否只能访问特定页面,如果他们是:
In my User model I have the users age, I want to test that a user can only visit a certain page if they are:
- 已登录
- 35 岁以上
我在 Devise 文档中看到我可以使用:*sign_in* 并且我已经把它放在我的测试中并且它似乎工作 - 测试没有错误,因为我有:
I have seen in the Devise document that I can use: *sign_in* and I have put it in my tests and it appears to work - the test doesn't error because I have:
include Devise::TestHelpers
在我的 *test_helper.rb*
in my *test_helper.rb*
当我取出它时,我的测试出现错误,因为 *sign_in* 未定义.所以不是辅助问题.
When I take it out my test does error because *sign_in* is not defined. So it is not a helper problem.
当我运行测试并检查 span#loggedin 是否出现 1 次时,测试失败,因为出现了 0 次.span#loggedin 仅出现 *if user_signed_in?*
When I run the test and check to see if span#loggedin has one occurrence the test fails because there is 0 occurrences. span#loggedin only appears *if user_signed_in?*
我需要在我的装置或测试中添加什么来创建一个测试用户,该用户也是一个完全注册的用户(已确认等)?
What do I need to put in my fixtures or tests to create a test user who is also a fully signed up user (confirmed etc)?
查看代码:
<% if user_signed_in? %>
<span id="loggedin">User is signed in</span>
User age is <span id="age"><%= current_user.age.to_s %></span>
<% end %>
测试代码:
test "should get index" do
sign_in :one
get :index
assert_response :success
assert_select 'span#loggedin', :count => 1
end
固定装置:
one:
email: jez@example.com
age: 36
当我手动登录时,它在开发中工作正常,但我希望将其全部自动化 - 真正的测试点!!
It works okay in development when I manually login but I'm hoping to automate it all - the point of testing really!!
推荐答案
Devise pre 3.2.0 的解决方案
我认为这可能是您要找的:
I think this might be what you are looking for:
User.new.send(:password_digest, 'password')
当盐为零时它起作用.
因此在你的装置中你可以这样做:
And therefore in your fixture you can do this:
one:
email: 'some@user.com'
encrypted_password: <%= User.new.send(:password_digest, 'password') %>
<小时>
Devise 3.2.0 到 3.5.0 版本的解决方案
在 Devise 3.2.0 中,一个方法正是为此目的而创建的@Inkling 更新).对于这些版本,encrypted_password 应该像这样定义:
At Devise 3.2.0, a method was created precisely for this purpose (@Inkling update). For these versions the encrypted_password should be defined like this:
encrypted_password: <%= Devise.bcrypt(User, 'password') %>
其中 User
是您的用户模型的类.
where User
is the class of your user model.
请注意,这仅适用于您使用默认加密算法 (bcrypt) 的情况.
Devise 3.5.1 及以上版本的解决方案
正如 Katarzyna 指出的那样:Device.bcrypt 已被弃用.5.a1.3 版本已弃用.从那个版本开始,encrypted_password 应该像这样定义:
As Katarzyna has pointed out: Device.bcrypt has been deprecated in version 3.5.1. From that version on, the encrypted_password should be defined like this:
encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>
这篇关于使用 Rails 和 Devise 进行功能测试.在我的固定装置中放什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!