如何测试RSpec中的attr_accessible字段
因此,我们通过Rails 3.2应用程序在许多字段上设置了attr_accessible
和attr_protected
。 目前我们确实没有测试以确保这些字段受到保护。
所以我决定谷歌一些答案,偶然发现这个解决方案:
RSpec::Matchers.define :be_accessible do |attribute| match do |response| response.send("#{attribute}=", :foo) response.send("#{attribute}").eql? :foo end description { "be accessible :#{attribute}" } failure_message_for_should { ":#{attribute} should be accessible" } failure_message_for_should_not { ":#{attribute} should not be accessible" } end
但是这个解决方案只测试方法是否响应。 我需要的是一种方法,让我测试属性可以和不能被大量分配。 老实说,我喜欢这种语法
it { should_not be_accessible :field_name } it { should be_accessible :some_field }
有没有人有更好的解决方案来解决这个问题?
您可以检查该属性是否在#accessible_attributes
列表中
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
我正在寻找类似的东西然后我被告知了shoulda-matcher allow_mass_assigment_of。 最终为我工作而没有创建自定义匹配器。
it { should allow_mass_assignment_of :some_field } it { should_not allow_mass_assignment_of :field_name }
希望这有助于其他人。
如果出于某种原因,RSpec正在跳上juicedM3的答案,就像我的那样,你可以这样做:
specify { expect { Model.new(unaccessible_attr: value) }.to raise_error(ActiveModel::MassAssignmentSecurity::Error) }
- 无法修改冻结数组(TypeError) – config / application.rb:42:in << <<':
- 如何为简单的PUT更新编写RSpec测试?
- RSpec :: ExampleGroups :: User :: Validations的未定义方法`validate_presence_of’
- 在发出请求之前,Rspec 2.7访问控制器会话
- .env没有在带有rspec的Rails中加载到测试环境中
- 不兼容的库版本:nokogiri.bundle需要11.0.0或更高版本,但libxml2.2.dylib
- Rspec 3弃用警告:不推荐使用example_group子分区过滤。 请使用subhash直接过滤
- 如何打破RSpec超长规格?
- 无效选项: – autospec