我已经实施了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 < 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
厂:
FactoryGirl.define do
factory :user do |f|
f.email { Faker::Internet.email }
f.password "secret"
f.role 1
end
end
我理解为什么会出现这种错误,并尝试了各种方法,但对工厂的理解并不充分。你能帮忙吗?
答案 0 :(得分:0)
所以问题与在创建项目时不使用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