Home > database >  Fix linting errors with "subject" in RSpec/Rails
Fix linting errors with "subject" in RSpec/Rails

Time:09-29

Trying to cleanup listing issues in an old codebase:

spec/models/story_spec.rb:8:16: C: RSpec/SubjectStub: Do not stub methods of the object under test.
      before { allow(subject).to receive(:end_date).and_return(Date.current) }
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
spec/models/story_spec.rb:8:22: C: RSpec/NamedSubject: Name your test subject if you need to reference it explicitly.
      before { allow(subject).to receive(:end_date).and_return(Date.current) }
                     ^^^^^^^

RSpec/SubjectStub

RSpec/NamedSubject

spec.rb:

describe Story, type: :model do
  describe 'validations' do
    it { is_expected.to belong_to(:user) }

    context 'when end_date is set' do
      before { allow(subject).to receive(:end_date).and_return(Date.current) }

      it { is_expected.to validate_presence_of(:start_date) }
    end

...

I'm not quite sure how to fix. Tried using subject(:story) and simply allow(:story) but I think I'm interpreting the explicit subject wrong.

CodePudding user response:

Instead of stubbing just set the object under test up explicitly:

describe Story, type: :model do
  describe 'associations' do
    it { is_expected.to belong_to(:user) } # this isn't a validation
  end

  describe 'validations' do
    context 'when end_date is set' do
      subject { Story.new(end_date: Date.current) } # This can also be done with FactoryBot traits
      it { is_expected.to validate_presence_of(:start_date) }
    end

...
  • Related