2

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 }
Ilya I
  • 1,282
  • 1
  • 12
  • 19

2 Answers2

2

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
Community
  • 1
  • 1
alf
  • 18,372
  • 10
  • 61
  • 92
  • 1
    Thanks, you are almost right, but specifying subject is required, it fails otherwise with `ArgumentError: wrong number of arguments (0 for 2)`. – Ilya I Oct 09 '13 at 12:57
0

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.

Cluster
  • 5,457
  • 1
  • 25
  • 36