RSpec

by msypniewski511 in Testing

Devise

login_as - helper

in spec/rails_helper.rb add:

RSpec.configure do |config|
...
  config.include Warden::Test::Helpers, type: :feature
  config.after(type: :feature) { Warden.test_reset! }
end

Better test

Guard

To achieve an instant test-running setup with RSpec that automatically detects code changes and reruns tests, you can use Guard with the guard-rspec gem. Here's how to set it up:


1. Add guard and guard-rspec to Your Gemfile

Add these gems to your Gemfile in the development or test group:

ruby

Copy code

group :development, :test do
gem 'guard'
gem 'guard-rspec', require: false
end

Then run:

bash

Copy code

bundle install


2. Initialize Guard

Run the following command to set up Guard in your project:

bash

Copy code

bundle exec guard init rspec

This generates a Guardfile in your project root, which Guard uses to configure file-watching behavior.


3. Customize the Guardfile

The default Guardfile will look something like this:

ruby

Copy code

guard :rspec, cmd: "bundle exec rspec" do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
end

This configuration:

  • Runs the related spec whenever you modify a test file or its corresponding code file.
  • Reruns all tests if you modify spec_helper.rb.

You can further customize it to fit your project structure. For example, if you're using Rails, add:

ruby

Copy code

watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^app/controllers/(.+)_controller\.rb$}) { |m| "spec/requests/#{m[1]}_spec.rb" }


4. Run Guard

Start Guard with:

bash

Copy code

bundle exec guard

Now, Guard will watch for file changes and automatically run the relevant tests.


5. Optional: Use spring for Faster Test Runs

To speed up test runs, include the spring gem in your Gemfile:

ruby

Copy code

gem 'spring'
gem 'spring-commands-rspec'

Then set it up:

bash

Copy code

bundle exec spring binstub rspec

Update your Guardfile to use Spring for running tests:

ruby

Copy code

guard :rspec, cmd: "bin/rspec" do
...
end


6. Optional: Notifications

If you'd like desktop notifications for test results (e.g., with macOS or Linux), ensure the rb-notifu, libnotify, or terminal-notifier gem is installed. For example:

bash

Copy code

gem install terminal-notifier

Guard will automatically use these to show test results as notifications.


7. Enjoy Instant Feedback!

Now, whenever you save a file, Guard will detect changes and rerun the relevant tests automatically.

0 Replies


Leave a replay

To replay you need to login. Don't have an account? Sign up for one.