From 4eb0ba53de1dbbfb1231cd36d4b9b71e4372ed8c Mon Sep 17 00:00:00 2001 From: Kim Burgestrand Date: Wed, 7 Aug 2024 15:58:43 +0200 Subject: [PATCH] Refactor rspec section to be more visually clear - Adds heading for custom description section. - Shortens custom description section a bit. - Increase priority/visibility of `pundit-matchers`. --- README.md | 41 +++++++++++++++++++---------------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 7dd32268..10cfadb0 100644 --- a/README.md +++ b/README.md @@ -761,6 +761,10 @@ end ### Policy Specs +> [!TIP] +> An alternative approach to Pundit policy specs is scoping them to a user context as outlined in this +[excellent post](https://thunderboltlabs.com/blog/2013/03/27/testing-pundit-policies-with-rspec/) and implemented in the third party [pundit-matchers](https://github.com/punditcommunity/pundit-matchers) gem. + Pundit includes a mini-DSL for writing expressive tests for your policies in RSpec. Require `pundit/rspec` in your `spec_helper.rb`: @@ -790,40 +794,33 @@ describe PostPolicy do end ``` -You can customize the description used for the `permit` matcher: +### Custom matcher description -``` ruby -Pundit::RSpec::Matchers.description = - "permit the user" +By default rspec includes an inspected `user` and `record` in the matcher description, which might become overly verbose: + +``` +PostPolicy + update? and show? + is expected to permit # and #> ``` -given the spec +You can override the default description with a static string, or a block: ```ruby -permissions :update?, :show? do - it { expect(policy).to permit(user, record) } +# static alternative: Pundit::RSpec::Matchers.description = "permit the user" +Pundit::RSpec::Matchers.description = ->(user, record) do + "permit user with role #{user.role} to access record with ID #{record.id}" end ``` -will change the output from - -``` -update? and show? - is expected to permit # and # -``` - -to +Which would make for a less chatty output: ``` -update? and show? - is expected to permit the user +PostPolicy + update? and show? + is expected to permit user with role admin to access record with ID 130 ``` -which may be desirable when distributing policy specs as documentation. - -An alternative approach to Pundit policy specs is scoping them to a user context as outlined in this -[excellent post](https://thunderboltlabs.com/blog/2013/03/27/testing-pundit-policies-with-rspec/) and implemented in the third party [pundit-matchers](https://github.com/punditcommunity/pundit-matchers) gem. - ### Scope Specs Pundit does not provide a DSL for testing scopes. Test them like you would a regular Ruby class!