A (Brief!) Intro to RSpec

Doug Price / @solipet

a beautifully drawn frog, very realistic actually

December 8, 2015

Components of RSpec

Plus 283 other gems! Zomg!!!

rspec-core: ExampleGroup

describe, context

Creates an ExampleGroup. Within the block passed to describe, you can declare examples using the it method.

You can also declare nested groups using the describe or context methods.

``` ruby describe Post do context "published" do ... end context "draft" do ... end end ```

rspec-core: Example

it, specify, example
Creates an Example. Within the block passed to describe, you can declare examples using the it method.
``` ruby describe Post do context "published" do it "shows the date it was published" do ... end end end ```

rspec-core: Hooks

before, after, around

Methods to support common setup and teardown.

Available from any describe or context block, or off the configuration object to define global setup/teardown logic.

``` ruby describe Post do before do @post = Post.new end it "starts as a draft" do expect(@post.published).to be(false) end end ```
screenshot showing before scope ordering http://www.rubydoc.info/gems/rspec-core/RSpec/Core/Hooks#before-instance_method

rspec-core: MemoizedHelpers

let
Generates a method whose return value is memoized after the first call.
``` ruby describe Post do let(:post) { Post.new } it "is awesome" do expect(post).to be_awesome end end ```

rspec-core: MemoizedHelpers

subject
Declares a subject for an example group which can then be wrapped with expect using is_expected to make it the target of an expectation in a concise, one-line example.
``` ruby describe Post do subject { Post.new } it { is_expected.to be_awesome } end ```

Note: is_expected is defined in rspec-core, but only works if rspec-expectations is included!

rspec-expectations: Matchers

Type Example
Equivalance `expect(actual).to eq(expected) # passes if actual == expected`
Identity `expect(actual).to be(expected) # passes if actual.equal?(expected)`
Comparisons `expect(actual).to be > expected`
Regular Expressions `expect(actual).to match(/expression/)`
Types/classes `expect(actual).to be_a(expected) # passes if actual.kind_of?(expected)`
Truthiness `expect(actual).to be true # passes if actual == true`
Errors `expect { ... }.to raise_error(ErrorClass, "message")`
Throws `expect { ... }.to throw_symbol(:symbol, 'value')`
Yielding `expect { |b| 5.tap(&b) }.to yield_control`
Predicate `expect(actual).to be_xxx # passes if actual.xxx?`
Ranges `expect(1..10).to cover(3)`
Collection `expect(actual).to include(expected)`

rspec-expectations: Should matchers

Starting in v2.11, the expect method was introduced and is now recommended. The older should syntax is still supported.

ShouldExpect
`actual.should eq(expected)``expect(actual).to eq(expected)`
`actual.should match(/expression/)``expect(actual).to match(/expression/)`

rspec-rails: setup

``` bash $ vim Gemfile group :development, :test do gem 'rspec-rails', '~> 3.0' end $ bundle install --binstubs ... $ rails generate rspec:install Looks like your app's ./bin/rails is a stub that was generated by Bundler. In Rails 4, your app's bin/ directory contains executables that are versioned like any other source code, rather than stubs that are generated on demand. Here's how to upgrade: bundle config --delete bin # Turn off Bundler's stub generator rake rails:update:bin # Use the new Rails 4 executables git add bin # Add bin/ to source control You may need to remove bin/ from your .gitignore as well. ... $ cat .rspec --color --require spec_helper $ cat spec/spec_helper.rb # This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end ```

Running tests

``` bash $ rake spec $ rake spec:models $ rake -T | grep spec ```

rspec-rails Spec Types

Model Used to describe behavior of models in the application.
ControllerUsed to describe behavior of Rails controllers.
Feature Used to test your application from the outside by simulating a browser.
Request Used to specify one or more request/response cycles from end to end using a black box approach.
View Used to test the rendering of your view templates.
Routing Used to test the routes against controller actions.
Helper Used to validate the behavior of helper methods.
http://rspec.info/documentation/3.4/rspec-rails/

Demo??!

References