rspec测试之间的共享示例方法

时间:2015-06-05 17:54:02

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

我正在测试的每个模型都具有相同的“它必须具有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的内容,但我不确定这是否是我正在寻找的内容。也许我只是想以错误的方式做这件事。

- UPDATE -

如果我将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).

1 个答案:

答案 0 :(得分:0)

共享示例用于跨不同模型测试相同的逻辑。在这里,您只是测试一个模型,因此它不适用于您。即使我不建议测试核心验证器,例如存在,您也可以这样做

# /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库的一部分。