← Back to Upcase

Rspec Sharing Methods Between Files

(Nicolo) #1

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.

(Mark Thomas) #2

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


(Richard Lamb) #3

I used the workshop method:

in spec/support/signin_helpers.rb

module SigninHelpers
  def sign_in

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

RSpec.configure do |config|
  config.include SigninHelpers

Then in any of my test files:


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

(Chad Pytel) #4

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:

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: https://github.com/thoughtbot/learn/blob/master/spec/support/airbrake.rb

(Nicolo) #5

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.

(Charlie Hua) #6

I use shared_context to setup/stub for the tests…