请提供帮助。
我为动作编辑编写了测试:
setup do
@user = users(:one)
end
test "should get edit" do
get :edit, id: @user
assert_response :success
assert_template :edit
assert_template layout: "layouts/application"
end
users.yml里:
one:
name: 'onfge'
email: 'MyStrdfing@ad.ad'
password_digest: '$2a$10$XS2HLwMZxg/7yRKAWd9AJ.afCMra0wGWK4b.FhkY/qo3Lmo/tKEiO'
remember_token: 'dc3461e13c8d316dad22332a503e06edafa0b9cb'
phone: '43535345'
skype: 'gggggg'
gender: one
info: 'MyString'
admin: true
avatar_file_name: nil
avatar_content_type: nil
avatar_file_size: nil
问题是页面/users/2/edit
仅访问经过身份验证的用户。现在它被重定向到身份验证页面。
请告诉我如何在测试中实现成功的身份验证?我试着做以下事情:
测试/ test_helper.rb中:
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
module SignInHelper
def sign_in(user)
session[:user_id] = user.id
end
end
class ActionController::TestCase
include SignInHelper
end
end
users_controller_test.rb:
test "should get edit" do
sign_in(@user)
get :edit, id: @user
assert_response :success
assert_template :edit
assert_template layout: "layouts/application"
end
但是进入控制台时出现以下错误消息:
rake test:controllers
1) Failure:
UsersControllerTest#test_should_get_edit [/home/kalinin/rails/ZSUM/test/controllers/users_controller_test.rb:59]:
Expected response to be a <success>, but was <302>
用于身份验证我使用SessionController:
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
flash[:success] = "Welcome to the Sample App!"
redirect_to user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end