ruby-on-rails – 使用ActionController :: InvalidAuthenticityToken失败的脚手架测试

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 使用ActionController :: InvalidAuthenticityToken失败的脚手架测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Rails 4.1.6中,我在运行使用scaffold生成的测试时遇到InvalidAuthenticityToken错误.有没有办法禁用特定测试的真实性令牌检查? @H_404_2@rails g scaffold user name:string email:string password_digest:string rake

输出

@H_404_2@... 1) Error: UsersControllerTest#test_should_create_user: ActionController::InvalidAuthenticityToken: ActionController::InvalidAuthenticityToken test/controllers/users_controller_test.rb:21:in `block (2 levels) in <class:UsersControllerTest>' test/controllers/users_controller_test.rb:20:in `block in <class:UsersControllerTest>' ...

这是源代码

@H_404_2@test "should create admin_user" do assert_difference('Admin::User.count') do post :create,admin_user: { email: @admin_user.email,password_digest: @admin_user.password_digest,username: @admin_user.username } end assert_redirected_to admin_user_path(assigns(:admin_user)) end

解决方法

有一些选择:

– >您可以将检测CSRF无效令牌的行为更改为重置会话(就像在Rails 3中一样):

在application_controller.rb中

@H_404_2@protect_from_forgery with: :exception

@H_404_2@protect_from_forgery with: :null_session

– >您可以使用条件表达式执行此操作,例如:

@H_404_2@if Rails.env.test? protect_from_forgery with: :null_session else protect_from_forgery with: :exception end

然而,这为测试和开发/生产环境提供了一些不同的配置.

– >您可以在测试中手动提供真实性令牌:

@H_404_2@def set_form_authenticity_token session[:_csrf_token] = SecureRandom.base64(32) end

特别是测试:

@H_404_2@post :create,username: @admin_user.username },authenticity_token: set_form_authenticity_token

– >你可以编写自己的助手,例如:

@H_404_2@def set_form_authenticity_token session[:_csrf_token] = SecureRandom.base64(32) end alias_method :post_without_token,:post def post_with_token(symbol,args_hash) args_hash.merge!(authenticity_token: set_form_authenticity_token) post_without_token(symbol,args_hash) end alias_method :post,:post_with_token

猜你在找的Ruby相关文章