How to test attr_accessible fields in RSpec

后端 未结 3 1478
春和景丽
春和景丽 2020-12-28 15:26

So we have been setting up attr_accessible and attr_protected on many fields through out our Rails 3.2 app. For now we really don\'t test to ensure

相关标签:
3条回答
  • 2020-12-28 16:08

    If for some reason RSpec is tripping up on juicedM3's answer above like mine was you can do something like this:

    specify { expect { Model.new(unaccessible_attr: value) }.to raise_error(ActiveModel::MassAssignmentSecurity::Error) }
    
    0 讨论(0)
  • 2020-12-28 16:14

    You can check if the attribute is on #accessible_attributes list

    RSpec::Matchers.define :be_accessible do |attribute|
      match do |response|
        response.class.accessible_attributes.include?(attribute)
      end
      description { "be accessible :#{attribute}" }
      failure_message_for_should { ":#{attribute} should be accessible" }
      failure_message_for_should_not { ":#{attribute} should not be accessible" }
    end
    
    0 讨论(0)
  • 2020-12-28 16:17

    I was looking for something similar and then I was told about the shoulda-matcher allow_mass_assigment_of. That ended up working for me without creating a custom matcher.

    it { should allow_mass_assignment_of :some_field }
    it { should_not allow_mass_assignment_of :field_name }
    

    Hope this helps someone else.

    0 讨论(0)
提交回复
热议问题