gpt4 book ai didi

ruby-on-rails - 脚手架测试失败,ActionController::InvalidAuthenticityToken

转载 作者:行者123 更新时间:2023-12-03 16:10:07 27 4
gpt4 key购买 nike

在 Rails 4.1.6 中,我收到 InvalidAuthenticityToken运行使用脚手架生成的测试时出错。有没有办法禁用特定测试的真实性 token 检查?

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 无效 token 的行为更改为重置 session (就像在 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

但是,这为测试和开发/生产环境提供了一些不同的配置。

-> 您可以在测试中手动提供真实性 token :
def set_form_authenticity_token
session[:_csrf_token] = SecureRandom.base64(32)
end

特别是测试:
post :create, admin_user: { email: @admin_user.email, password_digest: @admin_user.password_digest, 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

关于ruby-on-rails - 脚手架测试失败,ActionController::InvalidAuthenticityToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26472039/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com