Testing cancan abilities and getting MassAssignmentSecurity::Error

纵然是瞬间 提交于 2019-12-25 05:18:31

问题


I have implemented cancan and would like to test abilities as recommended on the cancan wiki. I trying to replicate "user can only destroy projects which he owns."

spec/models/ability_spec.rb:

require "cancan/matchers"
require 'spec_helper'

describe Ability do
  context "user is investigator" do
    it "user can only destroy projects which he owns" do
        user = FactoryGirl.create(:user)
        ability = Ability.new(user)
        ability.should be_able_to(:destroy, Project.new(:user => user))
    end
  end
end

However I get:

ActiveModel::MassAssignmentSecurity::Error:
       Can't mass-assign protected attributes: user

Models:

class User < ActiveRecord::Base
  has_many :projects, dependent: :destroy          
  devise :database_authenticatable, etc...         
  attr_accessible :email, :password, :password_confirmation, :remember_me, :locale 
  validates :role, :presence => true
end

class Project < ActiveRecord::Base
  belongs_to :user
end

Factory:

FactoryGirl.define do
  factory :user do |f|                        
    f.email { Faker::Internet.email }
    f.password "secret"
    f.role 1
  end
end

I understand why this error arrises, and have tried various ways round it, but don't have a good enough understanding of factories to crack it. Can you help?


回答1:


So the problem was related to not using Factory Girl when creating the project. It should have been:

describe Ability do
  context "user is investigator" do
    it "user can only destroy projects which he owns" do
        user = FactoryGirl.create(:user)
        ability = Ability.new(user)
        ability.should be_able_to(:destroy, FactoryGirl.create(:project, :user => user))
    end
  end
end


来源:https://stackoverflow.com/questions/12826708/testing-cancan-abilities-and-getting-massassignmentsecurityerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!