Skip to content

Instantly share code, notes, and snippets.

@HeroicEric
Created April 2, 2014 14:41
Show Gist options
  • Save HeroicEric/9935542 to your computer and use it in GitHub Desktop.
Save HeroicEric/9935542 to your computer and use it in GitHub Desktop.
An example of how to create a RSpec test helper

RSpec Helper Example

Here's an example of a rspec test helper that will let you sign in as a given user.

Create spec/support/helpers/authentication.rb with the following:

module Helpers
  module Authentication
    def sign_in_as(user)
      # here is where you can put the steps to fill out the log in form
    end
  end
end

Now you need to lead this module in your test config file. In spec/spec_helper.rb,

RSpec.configure do |config|
  # other stuff

  # Include our new authentication helper in all of our feature specs
  config.include Helpers::Authentication, type: :feature
end

Now you can use this method in your tests so that you don't have to repeat all of the steps to log a user in in each of your tests.

In spec/features/example_feature_spec.rb:

feature "something awesome" do
  scenario "signed in user views the index page" do
    user = FactoryGirl.create(:user)
    sign_in_as(user)
    
    visit root_path
    
    expect(page).to have_content "Welcome to my awesome website"
  end
end
@TiagoPR
Copy link

TiagoPR commented Jul 24, 2023

In case someone see's this, you now need to put the config.include Helpers::Authentication on the rails_helper.rb. At least to me it was giving me an NameError.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment