简体   繁体   中英

Rails and Rspec - can't mass-assign protected attributes

I am creating a Rails application with TDD using rspec. I am getting an error I can't remove:

Failure/Error: invalid_user = User.new(@attr.merge("provider" => ""))
 ActiveModel::MassAssignmentSecurity::Error:
   Can't mass-assign protected attributes: uid, info

Here is my user spec:

user_spec.rb

require 'spec_helper'

describe User do
  before(:each) do
  @attr = {"provider" => "providerexample", "uid" => "uidexample", "info" => {"name" =>     "Example"}}
 end

it "should create a new instance given valid attributes" do
  user = User.create_with_omniauth(@attr)
end

it "should require a provider" do
  invalid_user = User.new(@attr.merge("provider" => ""))
  invalid_user.should_not be_valid
end 

it "should require a uid" do
  invalid_user = User.new(@attr.merge("uid" => ""))
  invalid_user.should_not be_valid
end
end

And my user.rb

class User < ActiveRecord::Base
  attr_accessible :name, :credits, :email, :provider

  validates :name, :provider, :uid, :presence => true

  def self.create_with_omniauth(auth)
    create! do |user|
    user.provider = auth["provider"]
    user.uid      = auth["uid"]
    user.name     = auth["info"]["name"]
  end
 end

end

If I debug the mass-assign error by adding uid and info to the attr_accessible , I still get the following error unknown attribute: info .

If you merge what you had as @attr with info, then it'll exist for the create_with_omniauth call, but not the regular create methods.

describe User do
  let(:user_attributes) { {"provider" => "providerexample", "uid" => "uidexample"} }

  it "should create a new instance given valid attributes" do
    expect {
      User.create_with_omniauth(user_attributes.merge({"info" => {"name" => "example"}))
    }.to not_raise_error
  end
end

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