Punditのrspecをカイゼンしてみた のrspec3系版です
と言っても記述を差し替えただけのメモなので経緯は上記記事を
Macher
failure_message_for_should
や failure_message_for_should_not
は deprecated
ついでにrubocop
に従い助長ですが変数に入れて1行の長さを抑えています
spec/support/rspec_matcher.rb
RSpec::Matchers.define :authorize do |action|
match do |policy|
policy.public_send("#{action}?")
end
failure_message do |policy|
klass = policy.class
record = policy.record
inspect = policy.user.inspect
"#{klass} does not permit #{action} on #{record} for #{inspect}."
end
failure_message_when_negated do |policy|
klass = policy.class
record = policy.record
inspect = policy.user.inspect
"#{klass} does not forbid #{action} on #{record} for #{inspect}."
end
end
テスト
expect
記述に書き換えるだけです
ついでにdescribed_class
を使えばコピペ後に書き換える所が減ります
spec/pundit/article_policy_spec.rb
require 'rails_helper'
describe ArticlePolicy do
let(:record) { FactoryGirl.create(:article) }
subject { described_class.new(user, record) }
context 'for a visitor' do
let(:user) { nil }
it { is_expected.to authorize(:show) }
it { is_expected.to_not authorize(:create) }
it { is_expected.to_not authorize(:new) }
it { is_expected.to_not authorize(:update) }
it { is_expected.to_not authorize(:edit) }
it { is_expected.to_not authorize(:destroy) }
end
context 'for a user' do
let(:user) { FactoryGirl.create(:user) }
it { is_expected.to authorize(:show) }
it { is_expected.to authorize(:create) }
it { is_expected.to authorize(:new) }
it { is_expected.to authorize(:update) }
it { is_expected.to authorize(:edit) }
it { is_expected.to authorize(:destroy) }
end
end