Skip to content

Commit

Permalink
Refactor rspec section to be more visually clear
Browse files Browse the repository at this point in the history
- Adds heading for custom description section.
- Shortens custom description section a bit.
- Increase priority/visibility of `pundit-matchers`.
  • Loading branch information
Burgestrand committed Aug 8, 2024
1 parent e862a89 commit 4eb0ba5
Showing 1 changed file with 19 additions and 22 deletions.
41 changes: 19 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:

Expand Down Expand Up @@ -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 #<User:0x0000000104aefd80> and #<Post:0x0000000104aef8d0 @user=#<User:0x0000000104aefd80>>
```

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 #<User id: 105> and #<User id: 106>
```

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!
Expand Down

0 comments on commit 4eb0ba5

Please sign in to comment.