DEV Community

n350071🇯🇵
n350071🇯🇵

Posted on

1 1

shared_examples in RSpec

Pattern1: No arguments for it_should_behave_like

shared_examples_for "happy" do
  it{expect(dog.feel_good?).to be true}
end

context 'good status' do
  it_should_behave_like("happy"){ let(:dog){ Factorybot.create :dog, status: :eating }}
  it_should_behave_like("happy"){ let(:dog){ Factorybot.create :dog, status: :excited }}
  it_should_behave_like("happy"){ let(:dog){ Factorybot.create :dog, status: :running }}
end

Pattern2: with an argument for it_should_behave_like

shared_examples_for "0-23 hour" do |expectation|
  it{expect(hour.save).to be expectation}
end

describe 'hours' do
  it_should_behave_like("0-23 hour", false){ let(:hour){ Factorybot.create :hour, hour: -1 }}
  it_should_behave_like("0-23 hour", true) { let(:hour){ Factorybot.create :hour, hour: 0 }}
  it_should_behave_like("0-23 hour", true) { let(:hour){ Factorybot.create :hour, hour: 1 }}
  it_should_behave_like("0-23 hour", true) { let(:hour){ Factorybot.create :hour, hour: 22 }}
  it_should_behave_like("0-23 hour", true) { let(:hour){ Factorybot.create :hour, hour: 23 }}
  it_should_behave_like("0-23 hour", false){ let(:hour){ Factorybot.create :hour, hour: 24 }}
  it_should_behave_like("0-23 hour", false){ let(:hour){ Factorybot.create :hour, hour: 25 }}
end

🔗 Parent Note

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →