superstar3000
superstar3000

Reputation: 399

Rspec/Capybara Rails Where to put require 'capybara/rails'

In a Rails app does the require 'capybara/rails' go in spec/rails_helper.rb? Also how about the require 'capybara/rspec'? Does it go in spec/rspec_helper.rb? and not spec/rails_helper.rb ... what is the purpose of both of those files?

Upvotes: 2

Views: 2163

Answers (1)

Justin
Justin

Reputation: 4940

You can add it to the top of your rails_helper.rb file. Here are the setup instructions from their docs. Below is an example of the top of my rails_helper and the location of where I placed the require 'capybara/rspec'.

The purpose of the file is to load each test you run with a specific configuration. Thus you add the line require 'rails_helper' to the top of each test file like so:

require 'rails_helper'

RSpec.describe MyModel, :type => :model do
  # add your tests here
end

I found this resource helpful regarding the new use of two of these files. The file rails_helper.rb is new to RSpec 3x, whereas in RSpec 2x, the default helper file was spec_helper.rb.

Here is an example of the first few lines in one of my rails_helper.rb files. It should tell you where to place the code require 'capybara/rspec'

ENV['RAILS_ENV'] = 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)  
require 'rspec/rails'
require 'shoulda/matchers'
require 'capybara/rspec'

As an example of certain configuration for each test run, when I test image uploads, I want to delete the uploaded file after each test, so I configured my rails_helper.rb to do that.

config.after(:each) do
  if Rails.env.test? || Rails.env.cucumber?
    FileUtils.rm_rf(Dir["#{Rails.root}/spec/support/uploads"])
  end 
end

For some apps, I also like to use shoulda-matchers, and to use this feature, you have to make sure you require it for your tests, thus you add require 'shoulda/matchers to your rails_helper.rb.

Upvotes: 4

Related Questions