测试cancanfunction并获得MassAssignmentSecurity :: Error

我已经实现了cancan,并希望按照cancan wiki的推荐测试能力。 我试图复制“用户只能销毁他拥有的项目”。

规格/型号/ 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 

但是我得到:

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

楷模:

 class User  true end class Project < ActiveRecord::Base belongs_to :user end 

厂:

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

我理解为什么这个错误会产生,并且已经尝试了各种各样的方法,但是对工厂的理解并不充分。 你能帮我吗?

所以问题与在创建项目时不使用Factory Girl有关。 应该是:

 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