简体   繁体   中英

Rspec-rails 4 error: ActiveModel::ForbiddenAttributesError

I have an application running in rails 4.1 using mongoid as the orm. I created a model called User which has an attribute email . I am using RSpec for tests. I created the following spec

require 'spec_helper'

describe 'User' do

  before(:each) do
    @attr = { 
      user: {
        email: "rahul@gmail.com"
      }
    }
  end

  it "should create a valid User instance" do
    param = ActionController::Parameters.new(@attr)
    param.require(:user).permit!
    User.create!(param)
  end
end

when I run the spec, I get the following error

Failure/Error: User.create!(param) ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError

I know this is related to strong parameters but couldn't figure out what I am doing wrong.

From the fine manual :

require(key)

[...] returns the parameter at the given key [...]

So saying param.require(:user) does nothing at all to param , it merely does an existence check and returns param[:user] .

I think you want to say something more like this:

param = ActionController::Parameters.new(@attr)
User.create!(param.require(:user).permit!)

That usage would match the usual:

def some_controller_method
    @user = User.create(user_param)
end

def user_param
    param.require(:user).permit!
end

usage in controllers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM