2014-09-22 17 views
1

我試圖從Rails 4.1.11升級到4.1.16。升級後,我的一些SessionsController規範失敗。但是當我嘗試在開發環境中登錄時,一切似乎都正常。ForbiddenAttributesError,僅在測試中,次版本升級後

我有以下代碼:

# 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供應OmniAuth哈希:

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

當我嘗試使用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是代碼的其餘部分,如果你想看看。

回答

4

您是否嘗試過白名單這樣的參數?

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

@patrick這有什麼進展? – wicz 2014-10-01 18:28:17

+0

我試過'ActionController :: Parameters.new(request.env [「omniauth.auth」])。permit(:provider,:uid,:info)'但是沒有包含':info'參數:'undefined {「provider」=>「facebook」,「uid」=>「1234567」}:ActionController :: ParametersActionController :: Parameters ...'方法'info'。 在任何情況下,避免修改工作代碼只是爲了讓先前通過的測試能夠正常工作將會很好。正如我所提到的,當前檢索auth哈希的方法與文檔中提供的方法相同,因此問題出現在測試或Rails中,而不是控制器代碼。 – 2014-10-05 19:44:39

+0

這是因爲'info'具有嵌套參數。嘗試使用'permit(:provider,:uid,info:[:email])''。我同意不必更改工作代碼就可以了,但環境已經改變,所以你的代碼必須適應它。 OTOH,這是一個更好的變化,所以我不會介意那麼多。最好! – wicz 2014-10-06 07:52:02

1

試着改變你的Gemfile RSpec的版本是:

gem "rspec-rails", '~> 2.14.0.rc1' 
+0

我已經在RSpec 3.1.0上了,降級會很不方便。無論如何,我不清楚這將如何幫助。 – 2014-09-22 05:44:02

+0

它可能與例如這個? http://stackoverflow.com/questions/17335329/activemodelforbiddenattributeserror-when-creating-new-user – userden 2014-09-22 05:55:47

+0

是的,它是相關的。 – 2014-09-22 06:57:38