2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Model/Validationのテストがボイラープレートすぎてダルいので頑張ってみた

2
Posted at

マクロ化してみる。

spec/supports/model_macros.rb
module ModelMacros
  def it_is_expected_to_be_invalid_with(attr_name, value)
    value_for_display = value
    value_for_display = 'nil' if value.nil?
    value_for_display = 'empty' if value.is_a?(String) && value.empty?

    context "when #{attr_name} is #{value_for_display}" do
      before { subject.send("#{attr_name}=", value) }

      it 'has an error' do
        expect(subject).not_to be_valid
        expect(subject.errors[attr_name].size).to be >= 1
      end
    end
  end
end

RSpec.configure do |config|
  config.extend ModelMacros, type: :model
end

↑こんな感じのを置いとく。

すると、Modelのテストがこうなる↓

spec/models/team_spec.rb

require 'rails_helper'

RSpec.describe Team do
  subject(:team) { create(:team) }

  it { is_expected.to respond_to(:id, :name) }
  it { is_expected.to be_valid }

  it_is_expected_to_be_invalid_with :name, nil
  it_is_expected_to_be_invalid_with :name, ''
  it_is_expected_to_be_invalid_with :name, FFaker::Lorem.characters(33)
end

とりあえず試しに書いてみただけなので、意見求む

2
2
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?