脚手架测试失败,使用ActionController :: InvalidAuthenticityToken

Sch*_*ute 6 ruby-on-rails ruby-on-rails-4

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

rails g scaffold user name:string email:string password_digest:string
rake
Run Code Online (Sandbox Code Playgroud)

输出:

...

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

...
Run Code Online (Sandbox Code Playgroud)

这是源代码:

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
Run Code Online (Sandbox Code Playgroud)

Ess*_*sse 8

有一些选择:

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

application_controller.rb

protect_from_forgery with: :exception
Run Code Online (Sandbox Code Playgroud)

protect_from_forgery with: :null_session
Run Code Online (Sandbox Code Playgroud)

- >你可以用条件表达式做到这一点,例如:

if Rails.env.test?
  protect_from_forgery with: :null_session
else 
  protect_from_forgery with: :exception
end
Run Code Online (Sandbox Code Playgroud)

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

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

def set_form_authenticity_token
  session[:_csrf_token] = SecureRandom.base64(32)
end
Run Code Online (Sandbox Code Playgroud)

特别是测试:

post :create, admin_user: { email: @admin_user.email, password_digest: @admin_user.password_digest, username: @admin_user.username }, authenticity_token:  set_form_authenticity_token
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)