Rails5 で rspec の before, after, around を使ってみる
Ruby Ruby on Rails
Published: 2019-05-27

やったこと

Rails5 で rspec の before, after, around を使ってみます。

確認環境

$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]

$ rails --version
Rails 5.2.3

$ gem list | grep rspec-rails
rspec-rails (3.8.2)

調査

spec/models/task_spec.rb

require 'rails_helper'

RSpec.describe Task, type: :model do

  around(:example) do |example|
    puts 'around example before'
    example.run
    puts 'around example after'
  end

  before(:context) do
    puts 'before context'
  end

  after(:context) do
    puts 'after context'
  end

  it 'gets return' do
    puts 'in the example'
  end
end

出力結果

$ bundle exec rspec spec/models/task_spec.rb -f d

Task
before context
around example before
in the example
around example after
  gets return
after context

Finished in 0.00188 seconds (files took 0.85554 seconds to load)
1 example, 0 failures

参考