微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

在Rails 4.1.6中,我在运行使用scaffold生成的测试时遇到InvalidAuthenticityToken错误.有没有办法禁用特定测试的真实性令牌检查?
rails g scaffold user name:string email:string password_digest:string
rake

输出

...

  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>'

...

这是源代码

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中

protect_from_forgery with: :exception

protect_from_forgery with: :null_session

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

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

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

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

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

特别是测试:

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

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

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

原文地址:https://www.jb51.cc/ruby/265325.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐