DEV Community


Passings args into Rspec Shared Examples

mxdavis profile image Malki Davis ・1 min read

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
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) }
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)

Editor guide