LoginSignup
4
4

More than 5 years have passed since last update.

RubyからRSpecを実行する

Posted at

RSpecをシェルからではなくRubyから実行したいときのやり方を調べた。
rspecコマンドはRSpec::Core::Runner.runを呼び出しているのでそれを使えばいい。

RSpecのバージョン: 3.0

require 'rspec'

# 引数の配列を渡す
RSpec::Core::Runner.run(['spec.rb'])
spec.rb
describe 'addition' do
  it 'adds 2 values' do
    expect(1 + 2).to eq(3)
  end
end

カスタムformatterを使う

カスタムformatterを実装してその場で使うこともできる。

require 'rspec'

class MyFormatter
  RSpec::Core::Formatters.register self, :example_passed

  def initialize(output)
  end

  def example_passed(notification)
    puts "passed: #{notification.example.description}"
  end
end

RSpec::Core::Runner.run(['spec.rb', '--format', 'MyFormatter'])

複数回実行する

複数回実行するときはRSpec.resetすればよいようだ。

require 'rspec'

RSpec::Core::Runner.run(['spec.rb'])
RSpec.reset
RSpec::Core::Runner.run(['spec.rb'])

参考

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4