Search code examples
ruby-on-railsrspecpundit

RSpec test for pundit using expect syntax


I'm trying to convert the following spec to new expect syntax, could anyone help?

describe PostPolicy do
  subject { PostPolicy }

  permissions :create? do
    it "denies access if post is published" do
      should_not permit(User.new(:admin => false), Post.new(:published => true))
    end

    it "grants access if post is published and user is an admin" do
      should permit(User.new(:admin => true), Post.new(:published => true))
    end

    it "grants access if post is unpublished" do
      should permit(User.new(:admin => false), Post.new(:published => false))
    end
  end
end

I tried that, but it didn't work because permit() returns a matcher -- RSpec::Matchers::DSL::Matcher:

specify { expect(permit(@user, @post)).to be_true }

Solution

  • You have to invoke the subject explicitly since the implicit receiver only works for should. More information here and here.

    In your example, this should work:

    describe PostPolicy do
      subject { PostPolicy }
    
      permissions :create? do
        it "denies access if post is published" do
          expect(subject).not_to permit(User.new(:admin => false), Post.new(:published => true))
        end
    
        it "grants access if post is published and user is an admin" do
          expect(subject).not_to permit(User.new(:admin => true), Post.new(:published => true))
        end
    
        it "grants access if post is unpublished" do
          expect(subject).not_to permit(User.new(:admin => false), Post.new(:published => false))
        end
      end
    end