Rspec-stubs
提供:Dev Guides
RSpec-スタブ
RSpec Doubles(別名Mocks)に関するセクションをすでに読んでいれば、RSpecスタブはすでに見ています。 RSpecでは、スタブはよく「メソッドスタブ」と呼ばれます。これは、既存のメソッド、またはまだ存在しないメソッドを「代用する」特別なタイプのメソッドです。
ここにRSpec Doublesに関するセクションからのコードがあります-
class ClassRoom
def initialize(students)
@students = students
End
def list_student_names
@students.map(&:name).join(',')
end
end
describe ClassRoom do
it 'the list_student_names method should work correctly' do
student1 = double('student')
student2 = double('student')
allow(student1).to receive(:name) { 'John Smith'}
allow(student2).to receive(:name) { 'Jill Smith'}
cr = ClassRoom.new [student1,student2]
expect(cr.list_student_names).to eq('John Smith,Jill Smith')
end
end
この例では、allow()メソッドはClassRoomクラスをテストするために必要なメソッドスタブを提供します。 この場合、Studentクラスのインスタンスのように動作するオブジェクトが必要ですが、そのクラスは実際には存在しません(まだ)。 Studentクラスはname()メソッドを提供する必要があることを知っており、allow()を使用してname()のメソッドスタブを作成します。
注意すべきことの1つは、RSpecの構文が長年にわたって少し変わったことです。 RSpecの古いバージョンでは、上記のメソッドスタブはこのように定義されます-
student1.stub(:name).and_return('John Smith')
student2.stub(:name).and_return('Jill Smith')
上記のコードを使用して、2つの* allow()*行を古いRSpec構文に置き換えてみましょう-
class ClassRoom
def initialize(students)
@students = students
end
def list_student_names
@students.map(&:name).join(',')
end
end
describe ClassRoom do
it 'the list_student_names method should work correctly' do
student1 = double('student')
student2 = double('student')
student1.stub(:name).and_return('John Smith')
student2.stub(:name).and_return('Jill Smith')
cr = ClassRoom.new [student1,student2]
expect(cr.list_student_names).to eq('John Smith,Jill Smith')
end
end
上記のコードを実行すると、この出力が表示されます-
.
Deprecation Warnings:
Using `stub` from rspec-mocks' old `:should` syntax without explicitly
enabling the syntax is deprec
ated. Use the new `:expect` syntax or explicitly enable `:should` instead.
Called from C:/rspec_tuto
rial/spec/double_spec.rb:15:in `block (2 levels) in <top (required)>'.
If you need more of the backtrace for any of these deprecations
to identify where to make the necessary changes, you can configure
`config.raise_errors_for_deprecations!`, and it will turn the
deprecation warnings into errors, giving you the full backtrace.
1 deprecation warning total
Finished in 0.002 seconds (files took 0.11401 seconds to load)
1 example, 0 failures
RSpecの例でメソッドスタブを作成する必要がある場合は、新しいallow()構文を使用することをお勧めしますが、ここでは古いスタイルを提供しているので、見たときにそれを認識できます。