Rspec Sharing Methods Between Files

Is there a recommended way to share setup methods for tests between rspec files?

I specifically speaking towards methods that are used to setup objects for tests. I’m looking for a better approach than just stuffing methods into something like spec_helper.

Have you used the shared examples classes before? Could be useful, unless you’re looking for something a little bit different than what they’re meant to accomplish

I used the workshop method:

in spec/support/signin_helpers.rb

module SigninHelpers
  def sign_in
    sign_in_as("test@test.com")
  end

  def sign_in_as(email)
    visit root_path
    fill_in('Email address', :with => email)
    click_button 'Sign in'
  end
end

RSpec.configure do |config|
  config.include SigninHelpers
end

Then in any of my test files:

sign_in

This could be modified to have methods for settings up object. Or am I missing the point? :smile:

We put these methods in well-named files in spec/support.

With this line in spec_helper.rb we include all files in spec/support automatically:

You can see an example of one of those files here:
https://github.com/thoughtbot/learn/blob/master/spec/support/license.rb

If you don’t put the methods in a module, as in the above, they’ll be available throughout your entire spec suite.

If you need or want to limit where they are available, you can put them in a module and configure their inclusion, as seen here:

You can also include them in a module and do the RSpec configuration in spec_helper. We’re doing this here:

If shared example groups make sense, you’ll also want to out them in files in spec/support, an example of one is here: upcase/airbrake.rb at master · thoughtbot/upcase · GitHub

Thanks for the answers. I’m not sure I really understand the shared groups yet, so I’ll probably stick to simple methods in spec/support.

I use shared_context to setup/stub for the tests…

FYI.