0

我正在使用 rspec 创建一个带有 TDD 的 Rails 应用程序。我收到一个无法删除的错误:

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

这是我的用户规格:

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

和我的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

结尾

mass-assign如果我通过添加uidinfo来调试错误attr_accessible,我仍然会收到以下错误unknown attribute: info

4

1 回答 1

1

如果你将你作为@attr 的内容与信息合并,那么它会存在于 create_with_omniauth 调用中,但不是常规的 create 方法。

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
于 2012-04-09T02:04:28.193 回答