6

属性が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

それを行うより良い方法はありますか?

...どうも

4

1 に答える 1

7

これは、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

これがあなたが探していたものではない場合、「より良い方法」があるかどうかを尋ねるときに、あなたがどのような解決策を求めているかについて、より良いアイデアを教えていただけますか?

編集

テストごとにコードを1行だけにクリーンアップするShouldaActiveModelマッチャーに興味があるかもしれません。何かのようなもの:

it { should_not allow_mass_assignment_of(:author) }
it { should allow_mass_assignment_of(:something_else) }
于 2012-08-07T15:51:07.517 に答える