Tintin81
Tintin81

Reputation: 10207

How to test for mass assignment errors in Rspec and Rails 4?

I recently upgraded my Rails app from Rails 3 to 4 and this Rspec test is no longer passing:

# spec/models/user_spec.rb:

require 'spec_helper'

describe User do

  it "should not allow access to admin" do
    expect do
      User.new(:admin => true)
    end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
  end

end

I am getting this error:

Failure/Error: end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
NameError: uninitialized constant ActiveModel::MassAssignmentSecurity

I suspect that this is somehow due to the switch to Rails 4's strong parameters.

How can I test for mass assignment errors now?

Thanks for any help.

Upvotes: 5

Views: 987

Answers (2)

SergeyKutsko
SergeyKutsko

Reputation: 697

To make your test pass you need add config.active_record.mass_assignment_sanitizer = :strict to
config/aplication.rb and add gem https://github.com/rails/protected_attributes to Gemfile.

If you want test strong parameters read this article http://pivotallabs.com/rails-4-testing-strong-parameters/

Upvotes: 2

Tintin81
Tintin81

Reputation: 10207

As Baldrick pointed out rightly there's no need in Rails 4 to test for mass assignment issues in Rspec model tests. The whole idea of Rails 4's Strong Parameters is to move all that functionality to the controller.

Upvotes: 3

Related Questions