RSpec/Shoulda验证是否存在多属性语法

RSpec/Shoulda验证是否存在多属性语法,rspec,shoulda,Rspec,Shoulda,当使用Shoulda/RSpec测试多个属性的验证是否存在时,我得到如下长而重复的代码块: it { should validate_presence_of(:text) } it { should validate_presence_of(:user) } it { should validate_presence_of(:commentable) } [...] 有没有办法把它擦干?大概是这样的: it { should validate_presence_of(:text, :user,

当使用Shoulda/RSpec测试多个属性的
验证
是否存在时,我得到如下长而重复的代码块:

it { should validate_presence_of(:text) }
it { should validate_presence_of(:user) }
it { should validate_presence_of(:commentable) }
[...]
有没有办法把它擦干?大概是这样的:

it { should validate_presence_of(:text, :user, :commentable,...) }

据我所知,没有什么内置的,以应为这一点。通常,您会希望将选项链接到shoulda宏,例如,
.with_message(…)
,因此您的语法建议不适用于这些情况

您可以改为执行以下操作:

[:text, :user, :commentable].each do |field|
  it { should validate_presence_of(field) }
end

然而,为了便于阅读和维护,我不会太担心在测试套件中有一点重复。

据我所知,没有任何内置的东西可以用于此。通常,您会希望将选项链接到shoulda宏,例如,
.with_message(…)
,因此您的语法建议不适用于这些情况

您可以改为执行以下操作:

[:text, :user, :commentable].each do |field|
  it { should validate_presence_of(field) }
end

但是,为了便于阅读和维护,我不太担心在测试套件中有一点重复。

您可以这样做:

  describe "Validations" do
    %i[text user strict_start commentable].each do |field|
      it { is_expected.to validate_presence_of(field) }
    end
  end

您可以这样做:

  describe "Validations" do
    %i[text user strict_start commentable].each do |field|
      it { is_expected.to validate_presence_of(field) }
    end
  end