2012-02-27 34 views
0

在Rails 3項目中對我的控制器代碼運行功能測試時,發生致命錯誤;所述params變量包含controlleraction,和加載ActiveModel不樂意了:Rails 3功能測試:無法批量分配受保護的屬性:控制器,動作

ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: controller, action 
    /Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.2.1/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes' 
    /Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.2.1/lib/active_model/mass_assignment_security/sanitizer.rb:20:in `debug_protected_attribute_removal' 
    /Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.2.1/lib/active_model/mass_assignment_security/sanitizer.rb:12:in `sanitize' 
    /Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.2.1/lib/active_model/mass_assignment_security.rb:228:in `sanitize_for_mass_assignment' 
    /Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.1/lib/active_record/attribute_assignment.rb:75:in `assign_attributes' 
    /Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.1/lib/active_record/base.rb:495:in `initialize' 
    /Users/phooze/Documents/rails-app/app/controllers/credentials_controller.rb:40:in `new' 

的應用程序調用是「新」方法(其中,該錯誤發生的),代碼:

# Credential#create (POST) 
    def create 
     @credential = Credential.new(params) 
     # ... controller continues 
    end 

最後,我的測試用例:

test "should create credential" do 
    assert_difference('Credential.count', 1) do 
     post :create, { :fid => "foobarbaz", :credentials_hash => "f00ba7f00ba7", :uid => "10023", :cid => "342" } 
    end 
    assert_response :created 
    end 

變更我控制器代碼到僅包含一個FID「單獨的」參數的散列,憑證s_hash,uid和cid使其工作。我很確定Rails試圖「很好」併爲我提供測試的附加值,但它似乎導致了問題。

有關如何解決此問題的任何建議?

回答

2

看起來你已經設置在測試環境中唯一的,而不是在開發或生產config.active_record.mass_assignment_sanitizer = :strict ,因爲params總是包含controlleraction,在任何環境中。

我認爲這裏的最佳實踐建議是始終使用form_for,這樣您就可以在params[:credential]或中獲得憑據。

+0

謝謝。我沒有使用params [:credential]的原因是它是一個Web API調用(在我的控制器中沒有「new」方法) - 並且一些參數是查詢字符串,所以「credential [uid]」isn對查詢字符串不合理......但不是我想要做的第一件事:) – makdad 2012-02-27 05:02:56

相關問題