2012-02-16 14 views
22

私たちは、Rails 3.2アプリケーションから多くのフィールドにattr_accessibleattr_protectedを設定しています。今のところ、これらのフィールドが保護されていることを確認するためのテストは実際にはありません。RSpecのattr_accessibleフィールドのテスト方法

だから私はいくつかの答えをグーグルすることを決定し、この溶液につまずい:

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 
+0

[Permitters]使用を検討してください(https://github.com/permitters/permitters) (attr_accessible + attr_protected)の代わりに[Strong Parameters](https://github.com/rails/strong_parameters)を使用してください。 –

+1

すでに実動環境で使用しています。これは、ForbiddenAttributesが主流ではないときからのものでした。 – WarmWaffles

答えて

32

私は似たような探していたし、私はshoulda-マッチャーallow_mass_assigment_ofについて言われました。それはカスタムマッチャーを作成せずに私のために働いてしまった。

it { should allow_mass_assignment_of :some_field } 
it { should_not allow_mass_assignment_of :field_name } 

これは他の人に役立つことを望みます。

+0

クール!あなたはこのコードをどこに入れますか? – emrass

+4

このコードを 'spec/support/be_accessible_matcher.rb'に置くことができます。 – shingara

+0

ここで配列 – WarmWaffles

27

上にあるかどうかをチェックすることができます

+0

これは多かれ少なかれ上記の私が想定すると実装されています。しかし、私はこれが存在するのか分からなかった。あなたのために投票してください – WarmWaffles

+1

宝石へのリンクを追加するだけです:https://github.com/thoughtbot/shoulda-matchers –

1

RSpecのは私は、あなたがこのような何かを行うことができたように、上記juicedM3の答えにアップトリップされ、何らかの理由場合:

specify { expect { Model.new(unaccessible_attr: value) }.to raise_error(ActiveModel::MassAssignmentSecurity::Error) } 
+0

これは新しい期待スタイルと一緒に行く方法です。 –

関連する問題