DEV Community

Malki Davis
Malki Davis

Posted on

Passings args into Rspec Shared Examples

It is convenient to have shared examples for testing to DRY up our tests and tests models or controllers that share code. An example could be an extend or include in a model or a before action in a controller.

Create your shared example in the support directory (make sure it auto loads by adding Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } to your spec_helper)

RSpec.shared_examples 'good stuff' do
  it 'runs some tests' do
    expect(arg).to be_valid
  end
end
Enter fullscreen mode Exit fullscreen mode

Then pass in args as a block in your test:

  it_behaves_like "good stuff" do
    let(:arg) { create(:something) }
  end
Enter fullscreen mode Exit fullscreen mode

Now you've got yourself a bunch of green tests with little effort!

Top comments (0)