ruby-on-rails - 使用expect语法对pundit进行RSpec测试

  显示原文与译文双语对照的内容
0 0

我正在尝试将以下规范转换为新的期望语法,任何人都可以帮助?


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 }

时间: 原作者:

0 0

你必须显式地调用 subject,因为隐式接收器只适用于 should 。 更多信息:这里是 ,这里是,这里是。

在你的示例中,这里操作应该有效:


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

原作者:
0 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) 。它使得一个接口更加方便。

原作者:
...