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 rails 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
The solution 😊 Jackson provides an annotation that can be used on class level (JsonIgnoreProperties). So simple, just add @JsonIgnoreProperties(ignoreUnknown = true) before the class.
Mass assignment vulnerabilites occur when a user is able to initialize or overwrite server-side variables for which are not intended by the application. By manually crafting a request to include additional parameters in a request, a malicious user may adversely affect application functionality.
The Mass Assignment vulnerability is a lack of data input validation that allows an attacker to modify data or elevate privileges by manipulating payload data.
Mass assignment is when you send an array to the model creation, basically setting a bunch of fields on the model in a single go, rather than one by one, something like: $user = new User(request()->all()); (This is instead of explicitly setting each value on the model separately.)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With