Rspec Shared example

RSpec 3.5 has been released!

RSpec.shared_context "DB support" do
  let(:db) { MyORM.database }
  # Wrap each example in a transaction...
  around do |ex|
    db.transaction(:rollback => :always, &ex)
  end
  # Interleave example begin/end messages in DB logs so it
  # is clear which SQL statements come from which examples.
  before do |ex|
    db.logger.info "Beginning example: #{ex.metadata[:full_description]}"
  end
  after do |ex|
    db.logger.info "Ending example: #{ex.metadata[:full_description]}"
  end
end

include_context

上述したshared_context 使うには include_context を使う。

RSpec.describe MyModel do
  include_context "DB support"
end

config.include_context

dbというメタデータが付いていたときに、自動で include_context する設定。

RSpec.configure do |config|
  config.include_context "DB support", :db
end

when_first_matching_example_defined

最初の一回に何かするときの設定。

RSpec.configure do |config|
  config.when_first_matching_example_defined(:db) do
    require "support/db"
  end
end

Filter by type or tag

Run only request(type: :request) specs.

$ bundle exec rspec -t type:request

tag option - Command line - RSpec Core - RSpec - Relish

$ rspec . --tag mytag # filter examples with non-existent tag
$ rspec . --tag ~skip # exclude examples with a simple tag