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'])