Search code examples
ruby-on-railsrspecmass-assignment

Rails Tutorial mass assignment security exception


I've been working through the Ruby on Rails Tutorial. I've run into a problem getting a test to pass that checks for the a mass assignment security exception to be thrown. I'm not sure why I'm getting this test failure, or how to fix it.

rspec:

describe "accessible attributes" do
    it "should not allow access to user_id" do
      expect do
        Micropost.new(user_id: user.id)
      end.should raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end    
  end

Failures:

  1) Micropost accessible attributes should not allow access to user_id
     Failure/Error: expect { Micropost.new(user_id: user.id) }.should raise_error(ActiveModel::MassAssignmentSecurity::Error)
       expected ActiveModel::MassAssignmentSecurity::Error, got #<NoMethodError: undefined method `call' for #<RSpec::Expectations::ExpectationTarget:0x8af2bb8>>
     # ./spec/models/micropost_spec.rb:23:in `block (3 levels) in <top (required)>

Solution

  • Try using to instead of should for your expect raise_error matcher.

    describe "accessible attributes" do
      it "should not allow access to user_id" do
        expect do
          Micropost.new(user_id: user.id)
        end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
      end    
    end