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

时间:2014-10-20 18:02:09

标签: ruby-on-rails ruby-on-rails-4

在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

1 个答案:

答案 0 :(得分:8)

有一些选择:

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

application_controller.rb

protect_from_forgery with: :exception

protect_from_forgery with: :null_session

- &GT;您可以使用条件表达式执行此操作,例如:

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

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

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

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

- &GT;您可以编写自己的帮助程序,例如:

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