I am writing a web app using BDD. In order to do just about anything in my app, the user needs to log in, so I was encouraged to write a function that will sign the user every time a rspec test is run. Basically, the code for the features test will end up looking like this:
DataSquid/spec/features/user_logs_in_spec.rb
require 'spec_helper'
feature "signing in" do
before :each do
@user = User.create(:name => 'user@example.com', :password => 'caplin')
end
scenario "user who logs in with correct credentials" do
sign_in(@user)
expect(page).to have_content 'Hi user@example.com'
end
end
First I read this article: http://robots.thoughtbot.com/rspec-integration-tests-with-capybara
Unfortunately, the author did not point out that they used FactoryGirl to work. In your Gemfile, add FactoryGirl:
# For testing
group :test, :development do
gem 'rspec-rails'
gem 'guard-rspec'
gem 'capybara'
gem 'selenium-webdriver'
gem 'database_cleaner'
gem "factory_girl_rails", "~> 4.0"
end
After running 'bundle install', you should be good to go. I then made this file, which holds the sign_in function.
DataSquid/spec/support/features/session_helpers.rb
module Features
module SessionHelpers
def sign_in(user=nil)
user ||= FactoryGirl.create(:user)
visit '/authentications/new'
fill_in 'Login', with: user.name
fill_in 'Password', with: user.password
click_button 'Sign in'
end
end
end
From what I can tell, the code in the file below makes the code in the session_helpers.rb file available to all of the feature tests.
DataSquid/spec/support/features.rb
RSpec.configure do |config|
config.include Features::SessionHelpers, type: :feature
end
Now I have a handy function I can call in my feature tests! Here is the link to my conversation on Stack Overflow about this issue: http://stackoverflow.com/questions/20390072/trouble-with-refactoring-code-for-rspec-feature-tests-in-rails-4.
No comments:
Post a Comment