← 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

https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples


(Richard Lamb) #3

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:


(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:
https://github.com/thoughtbot/learn/blob/master/spec/spec_helper.rb#L23

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

You can also include them in a module and do the RSpec configuration in spec_helper. We’re doing this here:
https://github.com/thoughtbot/learn/blob/master/spec/spec_helper.rb#L54

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…
https://www.relishapp.com/rspec/rspec-core/v/3-0/docs/example-groups/shared-context

FYI.