RSpecでmodelのattr_accessibleをテストする
RSpecでmodelのattr_accessibleをテストできないかと、調べていたところ
stackoverflowで良さげなマッチャがありました。
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
このコードをspec/support/be_accessible_matcher.rbで保存します。
以下がmodelの全てのカラムのaccessbileをテストするコードになります。
beforeでaccessibleなカラムのシンボルの配列を定義して下さい。
context 'attr_accessbie' do before do @obj = obj.new @accessible = [:aaa, :bbb, :ccc] end it 'check all columns accessible' do @obj.class.column_names.each do |name| if @accessible.include?(name.to_sym) @obj.should be_accessible name.to_sym else @obj.should_not be_accessible name.to_sym end end end end