詳しくはRSpec3.1の主な変更点のブログ記事にまとめましたが、要約をまとめておきます。
Backtraceフィルタの変更
gemの中のbacktraceをデフォルトで表示する。
–exclude-patternオプションの追加
$ rspec --pattern "spec/**/*_spec.rb" --exclude-pattern "spec/acceptance/**/*_spec.rb"
Rakefile
require ‘rspec/core/rake_task’
desc "Run all but the acceptance specs"
RSpec::Core::RakeTask.new(:all_but_acceptance) do |t|
t.exclude_pattern = "spec/acceptance/**/*_spec.rb"
end
スタンドアロンでも設定なしで動く
rspec-expectationやrspec-mocksがなくても動く
.rspecを–warningsフラグtrueで生成しない
Railsで.rspecを自動生成した時の--warningsのデフォルト値をtrueにしないように。
have_attributesマッチャの追加
Person = Struct.new(:name, :age)
person = Person.new("Alice", 20)
expect(person).to have_attributes(name: "Alice", age: 20)
## an_object_having_attributes
people = [Person.new("Alice", 20), Person.new("Bob", 30)]
expect(people).to match([
an_object_having_attributes(name: "Alice", age: 20),
an_object_having_attributes(name: "Bob", age: 30)
])
## receive with
expect(article).to receive(:author=).with(
an_object_having_attributes(name: "Alice")
)
Compoundマッチャをブロックでも利用可能
x = y = 0
expect {
x += 1
y += 2
}.to change { x }.to(1).and change { y }.to(2)
define_negated_matcherの追加
RSpec::Matchers.define_negated_matcher :exclude, :include
## example
expect(odd_numbers).to exclude(14)
## compound matcher example
adults = Town.find("Springfield").adults
marge = Character.find("Marge")
bart = Character.find("Bart")
expect(adults).to include(marge).and exclude(bart)
カスタムマッチャチェインをdescriptionにも出力
Spec::Matchers.define :be_smaller_than do |max|
chain :and_bigger_than do |min|
@min = min
end
match do |actual|
actual < max && actual > @min
end
end
Failure/Error: expect(5).to be_smaller_than(10).and_bigger_than(7)
expected 5 to be smaller than 10 and bigger than 7
spec_helper.rb
# デフォルトoffなので設定が必要
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
end
*_spyメソッドの追加
spy = double.as_null_object
expect(spy).to have_received(:foo)
spy(...) # double(...).as_null_object と同じ
instance_spy(...) # instance_double(...).as_null_object と同じ
class_spy(...) # class_double(...).as_null_object と同じ
object_spy(...) # object_double(...).as_null_object と同じ
and_wrap_originalの追加
allow(api_client).to receive(:fetch_users).and_wrap_original do |original_method, *args|
original_method.call(*args).first(10) # テスト時は10ユーザだけ取得する
end
Rails4.2の公式サポート
RSpec3.1からRails4.2を公式サポート。
rails_helper.rbではspec/supportを自動ロードしない
rails_helper.rbではspec/supportを自動ロードしないように。