375

I have the following file:

/spec/controllers/groups_controller_spec.rb

What command in terminal do I use to run just that spec and in what directory do I run the command?

My gem file:

# Test ENVIRONMENT GEMS
group :development, :test do
    gem "autotest"
    gem "rspec-rails", "~> 2.4"
    gem "cucumber-rails", ">=0.3.2"
    gem "webrat", ">=0.7.2"
    gem 'factory_girl_rails'
    gem 'email_spec'
end

Spec file:

require 'spec_helper'

describe GroupsController do
  include Devise::TestHelpers

  describe "GET yourgroups" do
    it "should be successful and return 3 items" do

      Rails.logger.info 'HAIL MARRY'

      get :yourgroups, :format => :json
      response.should be_success
      body = JSON.parse(response.body)
      body.should have(3).items # @user1 has 3 permissions to 3 groups
    end
  end
end
fresskoma
  • 25,481
  • 10
  • 85
  • 128
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012
  • You can run your tests like bundle exec rspec ./spec/controllers/groups_controller_spec.rb:6, it runs this specific test only. More info here: https://kolosek.com/rails-rspec-setup – Nesha Zoric Feb 21 '18 at 11:22
  • 1
    ``bundle exec rspec spec --help`` wil give you the answer: – Thomas Decaux May 09 '18 at 19:17

16 Answers16

578

Usually I do:

rspec ./spec/controllers/groups_controller_spec.rb:42

Where 42 represents the line of the test I want to run.

You can also use tags. See here.

Using bundle exec:

bundle exec rspec ./spec/controllers/groups_controller_spec.rb:42
Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • Thanks tried that it does not work when I do rake spec /spec/path...:XX I get the error /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -S bundle exec rspec ./spec/controllers/groups_controller_spec.rb ./spec/controllers/incoming_mails_controller_spec.rb ./spec/lib/mailing_job/mailingjob_find_reply_spec.rb ./spec/models/group_model_spec.rb ./spec/models/user_model_spec.rb – AnApprentice May 24 '11 at 20:54
  • If I try using just RSPEC, i get this error: "$ rspec spec/controllers/groups_controller_spec.rb:19 /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/runtime.rb:27:in `setup': You have already activated rspec-core 2.6.2, but your Gemfile requires rspec-core 2.6.0. Consider using bundle exec. (Gem::LoadError) " – AnApprentice May 24 '11 at 20:54
  • You can try "bundle exec rspec spec/controllers/groups_controller_spec.rb:19" in that case – muffinista May 24 '11 at 20:57
  • 1
    bundle exec worked but why? Is that a hack any way to avoid that? – AnApprentice May 24 '11 at 21:01
  • 12
    it's not a hack, it makes sure you use the very same version you declared in your gemfile. In your case, the mere `rspec` failed because the version on your system is more recent than the one in your gemfile. – apneadiving May 24 '11 at 21:04
  • IMO this solution is dangerous, because it can lead you to think that a test is passing when it actually isn't - for example, if you add a few lines of code ahead of the test you're trying to fix. Tags are a better way to go. – therin Sep 03 '13 at 20:48
  • @therin tags belong to my answer + if you assume you do things wrong, conclusion will always be wrong – apneadiving Jun 14 '14 at 08:25
  • Is there a way to do this using Django's test framework? – nnyby Jun 18 '14 at 21:02
  • Instead of `bundle exec`, you can use [binstubs](https://github.com/sstephenson/rbenv/wiki/Understanding-binstubs) – styger Oct 07 '14 at 19:18
  • If you are testing shared examples from an external file, this method will attempt to run a test at the specified line in the external file as well as the original referenced file. – Steve Sep 02 '15 at 23:27
  • I had to add a . (period) to the front of the path to get it to run ---------------------linebreak--------------------- `bundle exec rspec ./spec/controllers/groups_controller_spec.rb:42` – Ekkstein Nov 01 '16 at 14:15
  • There are a few reasons this is a bad answer and should not be the accepted answer— while it is often the quickest solution, you are bypassing the rake task and just instructing rspec to run the single test. In the past (prior to Rails 5), this worked fine. Running the rake task is better and less confusing for the dev long-term, the best is with `rake spec SPEC=` – Jason FB Mar 29 '20 at 16:44
  • check this `bundle exec rspec -f d spec/controllers/groups_controller_spec.rb` – Astm Feb 16 '22 at 16:31
76

With Rake:

rake spec SPEC=path/to/spec.rb

(Credit goes to this answer. Go vote him up.)

EDIT (thanks to @cirosantilli): To run one specific scenario within the spec, you have to supply a regex pattern match that matches the description.

rake spec SPEC=path/to/spec.rb \
          SPEC_OPTS="-e \"should be successful and return 3 items\""
Community
  • 1
  • 1
Grant Birchmeier
  • 17,809
  • 11
  • 63
  • 98
  • 12
    This is the superior answer because it uses the 'rake spec' command not the 'rspec' command. That means the test database is properly re-initialized each time (which doesnt happen if you use 'rspec...') – jpw Dec 11 '12 at 18:54
  • You can use `SPEC=path/to/spec.rb:42` to run the test on the given line number, although it seems any `it_behaves_like` tests will also get run (bug?). – mgold Nov 06 '15 at 05:00
75

You can pass a regex to the spec command which will only run it blocks matching the name you supply.

spec path/to/my_spec.rb -e "should be the correct answer"

2019 Update: Rspec2 switched from the 'spec' command to the 'rspec' command.

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
Douglas F Shearer
  • 25,952
  • 2
  • 48
  • 48
  • Thanks I tried that but it errors with: $ rake spec spec/controllers/incoming_mails_controller_spec.rb -e "should be successful and return 3 items" rake aborted! (eval):1:in `standard_rake_options': compile error (eval):1: syntax error, unexpected tIDENTIFIER, expecting $end should be successful and return 3 items – AnApprentice May 24 '11 at 20:52
  • Updated with the actual spec file ideas? – AnApprentice May 24 '11 at 20:53
  • If you have a compile error, your spec is not valid ruby. Make sure you are not missing a `do` after an `it`, `context` or `describe` declaration. – Douglas F Shearer May 24 '11 at 20:56
  • 1
    It's "spec", not "rake spec". – muffinista May 24 '11 at 21:01
  • this should be the correct answer, relating to a line number is seriously wrong - any any case – Eugen Mayer Jan 19 '17 at 09:30
  • That is amazing! But I think he wanted to run the test not only an example from the test (is a simple test example with only 1 example) – bott Aug 12 '19 at 10:49
  • This should be the correct answer, line number changes way too much to be useful. – Alien Jan 11 '22 at 19:26
35

There are many options:

rspec spec                           # All specs
rspec spec/models                    # All specs in the models directory
rspec spec/models/a_model_spec.rb    # All specs in the some_model model spec
rspec spec/models/a_model_spec.rb:nn # Run the spec that includes line 'nn'
rspec -e"text from a test"           # Runs specs that match the text
rspec spec --tag focus               # Runs specs that have :focus => true
rspec spec --tag focus:special       # Run specs that have :focus => special
rspec spec --tag focus ~skip         # Run tests except those with :focus => true
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
26

My preferred method for running specific tests is slightly different - I added the lines

  RSpec.configure do |config|
    config.filter_run :focus => true
    config.run_all_when_everything_filtered = true
  end

To my spec_helper file.

Now, whenever I want to run one specific test (or context, or spec), I can simply add the tag "focus" to it, and run my test as normal - only the focused test(s) will run. If I remove all the focus tags, the run_all_when_everything_filtered kicks in and runs all the tests as normal.

It's not quite as quick and easy as the command line options - it does require you to edit the file for the test you want to run. But it gives you a lot more control, I feel.

GlyphGryph
  • 4,714
  • 4
  • 32
  • 43
  • I definitely prefer this style, because I'm commonly running tests via Rubymine/intelliJ. I like this method also because its similar to using fit/xit in jasmine / with gulp – wired00 Sep 16 '15 at 15:02
23

Not sure how long this has bee available but there is an Rspec configuration for run filtering - so now you can add this to your spec_helper.rb:

RSpec.configure do |config|
  config.filter_run_when_matching :focus
end

And then add a focus tag to the it, context or describe to run only that block:

it 'runs a test', :focus do
  ...test code
end

RSpec documentation:

https://www.rubydoc.info/github/rspec/rspec-core/RSpec/Core/Configuration#filter_run_when_matching-instance_method

eazy_beans
  • 512
  • 4
  • 5
  • 4
    This requires changing infrastructure. And remembering to change it back. I would recommend not doing this and using just the `rspec` commands to run the spec with appropriate parameter to indicate which – Michael Durrant Dec 19 '19 at 12:17
10

@apneadiving answer is a neat way of solving this. However, now we have a new method in Rspec 3.3. We can simply run rspec spec/unit/baseball_spec.rb[#context:#it] instead of using a line number. Taken from here:

RSpec 3.3 introduces a new way to identify examples[...]

For example, this command:

$ rspec spec/unit/baseball_spec.rb[1:2,1:4] …would run the 2nd and 4th example or group defined under the 1st top-level group defined in spec/unit/baseball_spec.rb.

So instead of doing rspec spec/unit/baseball_spec.rb:42 where it (test in line 42) is the first test, we can simply do rspec spec/unit/baseball_spec.rb[1:1] or rspec spec/unit/baseball_spec.rb[1:1:1] depending on how nested the test case is.

Community
  • 1
  • 1
Ingo
  • 802
  • 9
  • 21
  • Note that if your shell is ZSH (as is now default with all Macs), you need to wrap the last argument in quotes to prevent the `zsh: no matches found` error. E.g. `rspec "spec/unit/baseball_spec.rb[1:1]"` – stwr667 Aug 17 '20 at 06:39
10

Run the commands from your project's root directory:

# run all specs in the project's spec folder
bundle exec rspec 

# run specs nested under a directory, like controllers
bundle exec rspec spec/controllers

# run a single test file
bundle exec rspec spec/controllers/groups_controller_spec.rb

# run a test or subset of tests within a file
# e.g., if the 'it', 'describe', or 'context' block you wish to test
# starts at line 45, run:
bundle exec rspec spec/controllers/groups_controller_spec.rb:45

Additionally, you can use the --example (-e) option to run specific tests that partially or fully match text labels in your 'it', 'describe', or 'context' blocks for the given test path:

# run groups controller specs in blocks with a label containing 'spaghetti flag is false'
bundle exec rspec spec/controllers/groups_controller_spec.rb -e 'spaghetti flag is false'

# Less granularly, you can run specs for blocks containing a substring of text 
# that matches one or more block labels, like 'spaghetti' or 'paghett'
bundle exec rspec spec/controllers/groups_controller_spec.rb -e spaghetti

This will run all the tests nested inside the blocks with labels matching the string argument received by the example option.

When using the example option, I recommend also appending --format documentation (shorthand: -f documentation) to your bundle command (e.g., bundle exec rspec spec/some_file.rb -e spaghetti -f documentation). Documentation-formatting replaces the normal ./F output with an easy-to-read pretty printed breakdown showing the nested block labels for the examples you're running and outputs the printed label for each example (it block) in green or red to denote whether it passed or failed. This provides better confirmation that your example argument matches the specs you intended to run, and it gives live visibility to which examples are passing/failing during longer test runs where the example argument matches many block labels and/or matched blocks contain many nested examples.

Additional Reading (Documentation Links)

Allison
  • 1,925
  • 1
  • 18
  • 25
9

For single example of spec file you need to add line number at the last , For Example

rspec spec/controllers/api/v1/card_list_controller_spec.rb:35

For single file you can specify your file path, For Example

rspec spec/controllers/api/v1/card_list_controller_spec.rb

For Whole Rspec Example in spec folder, you can try with this command

bundle exec rspec spec
Foram
  • 483
  • 5
  • 12
7

For model, it will run case on line number 5 only

bundle exec rspec spec/models/user_spec.rb:5

For controller : it will run case on line number 5 only

bundle exec rspec spec/controllers/users_controller_spec.rb:5

For signal model or controller remove line number from above

To run case on all models

bundle exec rspec spec/models

To run case on all controller

bundle exec rspec spec/controllers

To run all cases

 bundle exec rspec 
Sandeep Kapil
  • 984
  • 8
  • 14
5

In rails 5,

I used this way to run single test file(all the tests in one file)

rails test -n /TopicsControllerTest/ -v

Class name can be used to match to the desired file TopicsControllerTest

My class class TopicsControllerTest < ActionDispatch::IntegrationTest

Output :

enter image description here

If You want you can tweak the regex to match to single test method \TopicsControllerTest#test_Should_delete\

rails test -n /TopicsControllerTest#test_Should_delete/ -v
Alupotha
  • 9,710
  • 4
  • 47
  • 48
3

You can use

 rspec spec/controllers/groups_controller_spec.rb:<line_number>

line number should be line number of 'describe' or 'it' lines so that it will run tests present in that particular block. instead it will execute all the lines next to line_number.

also you can create block with custom name and then can execute those blocks only.

1

starting with rspec 2 you can use the following:

# in spec/spec_helper.rb
RSpec.configure do |config|
  config.filter_run :focus => true
  config.run_all_when_everything_filtered = true
end

# in spec/any_spec.rb
describe "something" do
  it "does something", :focus => true do
    # ....
  end
end
Rudi
  • 1,577
  • 3
  • 16
  • 42
0

I use this guard gem to auto-run my test. It execute test after create or update operations on test file.

https://github.com/guard/guard-test

or usually you can run using following command

rspec spec/controllers/groups_controller_spec.rb

Rameshwar Vyevhare
  • 2,699
  • 2
  • 28
  • 34
0

You can do something like this:

 rspec/spec/features/controller/spec_file_name.rb
 rspec/spec/features/controller_name.rb         #run all the specs in this controller
Prabhakar
  • 6,458
  • 2
  • 40
  • 51
0

Given you're on a rails 3 project with rspec 2, From the rails root directory:

  bundle exec rspec spec/controllers/groups_controller_spec.rb 

should definitely work. i got tired of typing that so i created an alias to shorten 'bundle exec rspec' to 'bersp'

'bundle exec' is so that it loads the exact gem environment specified in your gem file: http://gembundler.com/

Rspec2 switched from the 'spec' command to the 'rspec' command.

MissingHandle
  • 693
  • 4
  • 12