本文介绍了rails attr_accessible rspec 检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想用 RSpec 测试属性是否/是否可访问时,我是这样做的

When I want to test if attribute is / is not accessible with RSpec I'm doing it like this

class Foo
  attr_accesible :something_else
end

describe Foo do
  it('author should not be accessible')    {lambda{described_class.new(:author=>true)}.should raise_error ActiveModel::MassAssignmentSecurity::Error}
  it('something_else should be accessible'){lambda{described_class.new(:something_else=>true)}.should_not raise_error ActiveModel::MassAssignmentSecurity::Error}
end

有更好的方法吗?

...谢谢

推荐答案

这是 Rails 教程中进行属性可访问性测试的方式,我认为这非常好.因此,在您的情况下,测试代码可以稍微修改为:

This is the way attribute accessibility tests are done in the Rails Tutorial, which I think are pretty good. So, in your case, the test code could be modified slightly to read like:

describe Foo do
  describe "accessible attributes" do
    it "should not allow access to author" do
      expect do
        Foo.new(author: true)
      end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end

    it "should allow access to something_else" do
      expect do
        Foo.new(something_else: true)
      end.to_not raise_error(ActiveModel::MassAssignmentSecurity::Error)
    end
  end
end

如果这不是您想要的,当您询问是否有更好的方法"时,您能否让我们更好地了解您所寻求的解决方案?

If this isn't what you were looking for, can you give us a better idea of what kind of solution you're after when you ask if there is a "better way"?

您可能对 Shoulda ActiveModel 匹配器感兴趣,它会清理每次测试的代码只有一行.类似的东西:

You may be interested in the Shoulda ActiveModel matchers, which would clean up the code to just one line per test. Something like:

it { should_not allow_mass_assignment_of(:author) }
it { should allow_mass_assignment_of(:something_else) }

这篇关于rails attr_accessible rspec 检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 05:41