【问题标题】:Shared example methods between rspec testsrspec 测试之间共享的示例方法
【发布时间】:2015-06-05 17:54:01
【问题描述】:

我测试的每个模型都有相同的“它必须有atribute”测试,测试validates_presence_of 的某些属性。所以,我的目标是创建一个以模块化方式包含此测试的“助手”。

这是我所拥有的:

# /spec/helpers.rb
module TestHelpers

  # Runs generic validates_presence_of tests for models
  def validate_presence( object, attributes=[] )
    attributes.each do |attr|
      it "must have a #{attr}" do
            object.send("#{attr}=", nil)
            expect(object).not_to be_valid
          end
        end
      end

    end

# /spec/rails_helper.rb
# Added
require 'helpers'

# Added
RSpec.configure do |config|
  config.include TestHelpers
end

# /spec/models/business_spec.rb
require 'rails_helper'

RSpec.describe Business, type: :model do

  describe "Validations" do

  before :each do
    @business = FactoryGirl.build(:business)
  end

  # Presence
  validate_presence @business, %w(name primary_color secondary_color)

但是,我收到以下错误:

`validate_presence` is not available on an example group

我已阅读有关 shared_helpers 和使用 it_behaves_as 的信息,但我不确定这是否是我正在寻找的。也许我只是想以错误的方式这样做。

--更新--

如果我将 validate_presence 方法放入 it 块中,我会收到以下错误:

Failure/Error: it { validate_presence @business, %w(name primary_color secondary_color published) }
   `it` is not available from within an example (e.g. an `it` block) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). It is only available on an example group (e.g. a `describe` or `context` block).

【问题讨论】:

  • 验证应该在示例中,而不是在规范的序言中。
  • 如果我把它放在it 块中,我会得到一个不同的错误(添加到原始帖子中)
  • 你不应该检查object吗?
  • 戴夫,是的,但不是在这个最小的例子中。 :)

标签: ruby-on-rails ruby-on-rails-4 rspec


【解决方案1】:

共享示例用于跨不同模型测试相同逻辑。在这里,您只是在测试一个模型,因此它不适用于您。尽管我不建议测试 presence 之类的核心验证器,但您可以这样做

# /spec/models/business_spec.rb
require 'rails_helper'

RSpec.describe Business, type: :model do
  let(:business) { FactoryGirl.build(:business) }

  context "when validating" do  
    %w(name primary_color secondary_color).each |attribute|
      it "checks the presence of #{attribute} value" do 
        business.send("#{attribute}=", nil)

        expect(business).to_not be_valid
        expect(business.errors[attribute]).to be_any
      end
    end
  end
end

此外,您尝试使用的 validate_presence 助手是 shoulda-matchers 库的一部分。

【讨论】:

  • 这就是我在几个模型中所做的,这就是为什么我想进一步浓缩它并使用一种方法制作更动态的方法。除此之外,我还想以这种方式进行其他测试,这就是促使我寻求正确方法的原因。最后,我没有测试核心验证器,我只是确保验证器保留在模型中并且不会被意外删除。
猜你喜欢
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多