使用expect语法对权威的RSpec测试

时间:2013-10-09 12:13:10

标签: ruby-on-rails rspec pundit

我试图将以下规范转换为新的期望语法,有人可以帮忙吗?

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

我试过了,但它没有用,因为permit()返回了一个匹配器 - RSpec::Matchers::DSL::Matcher

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

2 个答案:

答案 0 :(得分:2)

您必须明确调用subject,因为隐式接收器仅适用于should。更多信息herehere

在您的示例中,这应该有效:

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

答案 1 :(得分:0)

另一种选择是使用隐式主语法。

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只需拨打expect(subject)即可。它使一个衬垫更方便。