【问题标题】:rails attr_accessible rspec checkrails attr_accessible rspec 检查
【发布时间】:2012-08-02 09:55:47
【问题描述】:

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

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

有没有更好的方法呢?

...谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 shoulda attr-accessible


    【解决方案1】:

    This is the way attribute accessibility tests are done in the Rails Tutorial,我觉得还不错。因此,在您的情况下,测试代码可以稍微修改为:

    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
    

    如果这不是您想要的,当您询问是否有“更好的方法”时,您能否更好地告诉我们您正在寻求什么样的解决方案?

    编辑

    您可能对Shoulda ActiveModel matchers 感兴趣,它会将代码清理为每次测试仅一行。比如:

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

    【讨论】:

    • +1 对于那些应该匹配的人,我认为不应该有这两个......作品
    • 这个问题实际上是我了解应该匹配器的原因,所以感谢您提出这个问题。我去重构了一些我的测试代码来使用它们。
    • 如果您觉得这个问题有用,请投票!作者应得的。
    • @Hosam Aly,你说得对,这是我的疏忽。问题已投票。
    猜你喜欢
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多