Question

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 }
Was it helpful?

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

OTHER TIPS

Another option is to use the implicit subject syntax.

describe PostPolicy do
  subject { PostPolicy }

  permission :create? do
    it { is_expected.not_to permit(User.new(admin: false), Post.new(published: true)) }
  end
end

is_expected simply calls expect(subject). It makes for a little more convenient one liners.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top