簡體   English   中英

rails attr_accessible rspec check

[英]rails attr_accessible rspec check

當我想測試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

這樣做有更好的方法嗎?

...謝謝

這是在Rails教程中完成屬性可訪問性測試的方式 ,我認為這非常好。 因此,在您的情況下,可以稍微修改測試代碼,如下所示:

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匹配器感興趣,它會將代碼清理為每個測試只有一行。 就像是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM