Skip to content

Instantly share code, notes, and snippets.

@elct9620
Created February 24, 2022 08:40
Show Gist options
  • Save elct9620/8ce44e6aa458362d473e080365175b7e to your computer and use it in GitHub Desktop.
Save elct9620/8ce44e6aa458362d473e080365175b7e to your computer and use it in GitHub Desktop.
RSpec have_attributes example
# API
class FakeResponse < Struct.new(:status, :code)
def success?
code == 200
end
end
class FakeAPI
def call
FakeResponse.new('Success', 200)
end
end
# Test
RSpec.describe FakeAPI do
subject(:api) { FakeAPI.new }
describe '#call' do
subject { api.call }
it { is_expected.to be_success }
it { is_expected.to have_attributes(status: match(/Success/)) }
it { is_expected.to have_attributes(code: 200) }
end
end
# Generated `--format document`
# FakeAPI
# #call
# is expected to be success
# is expected to have attributes {status: match(/Success/)}
# is expected to have attributes {code: 200 }
@elct9620
Copy link
Author

elct9620 commented Feb 24, 2022

To test a "nested" result, use describe but not suggested more than 3 levels.

RSpec.describe FakeAPI do
  subject(:api) { FakeAPI.new }
  
  describe '#call' do
    subject(:response) { api.call }
    
    it { is_expected.to be_success }
    it { is_expected.to have_attributes(status: match(/Success/)) }
    it { is_expected.to have_attributes(code: 200) }

    describe "#headers" do
      subject(:headers) { response.headers }

      it { is_expected.to include({ 'Content-Type' => 'application/json' }) }
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment