マクロ化してみる。
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
とりあえず試しに書いてみただけなので、意見求む