Rspec-subjects
提供:Dev Guides
RSpec-サブジェクト
RSpecの長所の1つは、テストを作成し、テストをクリーンにする多くの方法を提供することです。 テストが短く整理されていると、テストの記述方法の詳細ではなく、予想される動作に焦点を当てやすくなります。 RSpecのサブジェクトは、簡単な簡単なテストを作成できるもう1つのショートカットです。
このコードを検討してください-
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
end
describe Person do
it 'create a new person with a first and last name' do
person = Person.new 'John', 'Smith'
expect(person).to have_attributes(first_name: 'John')
expect(person).to have_attributes(last_name: 'Smith')
end
end
実際はかなり明確ですが、例のコードの量を減らすためにRSpecのサブジェクト機能を使用できます。 これを行うには、personオブジェクトのインスタンス化を記述行に移動します。
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
end
describe Person.new 'John', 'Smith' do
it { is_expected.to have_attributes(first_name: 'John') }
it { is_expected.to have_attributes(last_name: 'Smith') }
end
このコードを実行すると、この出力が表示されます-
..
Finished in 0.003 seconds (files took 0.11201 seconds to load)
2 examples, 0 failures
2番目のコードサンプルがどれほど単純であるかに注意してください。 最初の例で1つの* itブロック*を取得し、それを2つの* itブロック*に置き換えました。これにより、必要なコードが少なくなり、同様に明確になります。