Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 394
Tintin81 Avatar asked Dec 07 '13 13:12

Tintin81


2 Answers

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.

like image 147
Tintin81 Avatar answered Nov 04 '22 18:11

Tintin81


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/

like image 21
SergeyKutsko Avatar answered Nov 04 '22 18:11

SergeyKutsko