ForbiddenAttributesError,仅在测试中,在次要版本升级后

时间:2014-09-22 05:15:49

标签: ruby-on-rails rspec omniauth strong-parameters

我正在尝试从Rails 4.1.11升级到4.1.16。升级后,我的几个SessionsController规范都失败了。但是当我尝试登录开发环境时,一切似乎都能正常工作。

我有以下代码:

# sessions_controller.rb
def create
  @identity = Identity.find_or_create(auth)
  ...
end

protected

def auth
  request.env["omniauth.auth"]
end

# identity.rb
class Identity < ActiveRecord::Base
  ...
  def self.find_or_create(auth)
    where(auth.slice(:uid, :provider)).first_or_create
  end
end

在我的规范中,我使用spec_helper.rb中的一个fixture来提供OmniAuth哈希:

# spec_helper.rb
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new({
  :provider => 'facebook',
  :uid => '1234567',
  :info => {
    :email => 'joe@bloggs.com',
    ...
  }
}

当我尝试使用OmniAuth属性查找用户的身份时,我得到ForbiddenAttributesError

1) SessionsController GET :create not yet signed in sets the user ID in the session hash
   Failure/Error: get :create
   ActiveModel::ForbiddenAttributesError:
     ActiveModel::ForbiddenAttributesError
   # /Users/pat/.rvm/gems/ruby-2.1.2/gems/activemodel-4.1.6/lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment'

我理解params哈希中强参数和白名单属性的概念。但是我不能在OmniAuth哈希上使用require(至少不能直接使用),而我过去也没有。

这是OmniAuth's GitHub page上提供的示例:

class SessionsController < ApplicationController
  def create
    @user = User.find_or_create_from_auth_hash(auth_hash)
    self.current_user = @user
    redirect_to '/'
  end

  protected

  def auth_hash
    request.env['omniauth.auth']
  end
end

据推测,它适用于最新版本的Rails。

如何让我的测试通过?如果你想看看,Here是代码的其余部分。

2 个答案:

答案 0 :(得分:5)

您是否尝试过像这样的参数列入白名单?

def auth
  ActionController::Parameters.new(request.env["omniauth.auth"]).permit(...)
end

答案 1 :(得分:0)

尝试将gemfile中的rspec版本更改为:

gem "rspec-rails", '~> 2.14.0.rc1'
相关问题