LoginSignup
3
4

More than 5 years have passed since last update.

Punditのrspec3をカイゼンしてみた

Last updated at Posted at 2016-02-26

Punditのrspecをカイゼンしてみた のrspec3系版です
と言っても記述を差し替えただけのメモなので経緯は上記記事を

Macher

failure_message_for_shouldfailure_message_for_should_notdeprecated
ついでに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
3
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4