Ruby on rails 如何为授权用户编写测试?
请帮忙指教 我为动作编辑编写了测试:Ruby on rails 如何为授权用户编写测试?,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,请帮忙指教 我为动作编辑编写了测试: 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:
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/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
用户\控制器\测试.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>
您使用什么进行身份验证?你用的是Deviate吗?不是。我用的是自定义代码。你用什么进行身份验证?你用的是Deviate吗?不,我用的是自定义代码
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