我尝试使用设计运行rake测试(使用由数据库种子创建的用户)
运行rake test
会产生以下错误:
Failure:
CustomersControllerTest#test_should_get_index [/home/ubuntu/workspace/test/controllers/customers_controller_test.rb:7]:
Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/users/sign_in>
Response body: <html><body>You are being <a href="http://www.example.com/users/sign_in">redirected</a>.</body></html>
我的测试看起来像这样:
test "should get index" do
get customers_url
assert_response :success
end
这是一个非常简单的测试,但我不知道在执行测试之前如何实际登录网站。
答案 0 :(得分:1)
要测试需要经过身份验证的用户的操作,您可以使用Devise的sign_in
和sign_out
帮助程序。这些来自您的测试用例或其父类的Devise::Test::ControllerHelpers
(或Rails 5 +的Devise::Test::IntegrationHelpers
):
class CustomersControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers # <-- Include helpers
test "should get index" do
sign_in User.create(...) # <-- Create and authenticate a user
get customers_url
assert_response :success
end
end
有关详细信息,请参阅Devise自述文件中的controller tests部分。