Testing against mass assignment
Maybe this isn't something that needs to be tested against, but I'm learning so I don't think its wrong to test to the max.
I have several tests that all produce the expected results except for one. I found a way of working around it but I wondered what the correct method would be.
When I test saving in rai开发者_开发问答ls console it doesn't save the admin field from the params hash, which is what I expect. When I build with a factory then save it, validations pass/fail accordingly. When I test for protection against mass assignment the test fails (because it sets the admin field when I expect it not to)
Any thoughts, suggestions or concerns?
Thanks
Model:
class User ...
#id, name, email, admin(int)
attr_accesible :name, email
...
end
user_spec
it "should not have an admin after a mass save" do
user = Factory.build(:user)
user.save
user.admin.should be_nil #its not nil, its 0
end
factories
Factory.define :user do |f|
f.name "rec_acro"
f.email "rec@acro.com"
f.admin 0
end
You can use Shoulda on top of rspec to get a concise mass assignment spec:
describe User do
it { should_not allow_mass_assignment_of(:admin) }
end
FactoryGirl will take each attribute in the Factory definition and set it individually. So your test actually doesn't test mass assignment
From the FactoryGirl code (build.rb):
def set(attribute, value)
@instance.send(:"#{attribute}=", value)
end
(See this if you're interested in more code reading for the FactoryGirl gem.)
As another answer suggested, you can use the Shoulda to employ the allow_mass_assignment_of matcher. It basically does something like:
it "allows mass assignment of :title" do
accessible = Post.accessible_attributes.include?('title') ||
!Post.protected_attributes.include?('title')
accessible.should be_true
end
(Here's a little more about about Should matchers.)
Factory Girl (rightfully so) doesn't use mass assignment to generate objects. Take the generated user object from the factory and then attempt to do mass assignment on it, albeit with just the admin parameter.
精彩评论