I have a user model:
class User < ActiveRecord::Base
attr_accessible :email, :name
# admin only
attr_accessible :email, :name, :admin, :as => :admin
And the following model spec:
describe "accessible attributes" do
let(:new_user){ FactoryGirl.create(:user) }
@admin_attrs = { admin: true, name: "ben", email: "xyz@test.com"}
it "can not be set on create" do
# variant 1 - test fails, AM::MAS::Error NOT thrown
expect do
User.new(@admin_attrs)
end.should raise_error(ActiveModel::MassAssignmentSecurity::Error)
# variant 2 - test passes, AM::MAS::Error NOT thrown
expect do
User.new(admin: true, name: "ben", email: "xyz@test.com", password: "123xyz", password_confirmation: "123xyz")
end.should raise_error(ActiveModel::MassAssignmentSecurity::Error)
end
I can’t figure out why variant 1 of my test fails, but variants 2 passes. The error message I get is:
1) User accessible attributes can not be set on create
Failure/Error: expect do
expected ActiveModel::MassAssignmentSecurity::Error but nothing was raised
They are basically the same test. What am I doing wrong? In fact, if I perform test 1 from the console, it does throw a MAS::Error, as expected. I’m confused.
@admin_attrs is probably nil as far as your first text example is concerned because it’s not being set up in a before hook (or through ‘let’)