RR (Double Ruby、ダブルRuby)は、豊富なダブル化技術と簡潔な文法を備えたテストダブルフレームワークです。
-
double-ruby-users@rubyforge.org
-
double-ruby-devel@rubyforge.org
テストダブルとは、他のオブジェクトのテストを簡単にするために本当のオブジェクトを置き換えたものを一般化したものです。テストにおいてスタントのダブルのようなものです。次のものはテストダブルです:
-
モック
-
スタブ
-
フェイク
-
スパイ
-
プロキシ
xunitpatterns.com/Test%20Double.html
現在、RRでは、モック、スタブ、プロキシ、そして、スパイを実装しています。フェイクは通常カスタム化されたコードが必要ですので、RRのスコープを超えています。
class Test::Unit::TestCase include RR::Adapters::TestUnit end
Spec::Runner.configure do |config| config.mock_with :rr # もしくは、バージョンの非互換性で動作しない場合は # config.mock_with RR::Adapters::Rspec end
extend RR::Adapters::RRMethods mock(object).method_name {:return_value} object.method_name # :return_value が返ります RR.verify # ダブルの期待を満たしているかを検証します
RRのゴールの一つとして、より判読しやすいダブルを作ることです。これはダブルの宣言をできるだけ実際のメソッド呼び出しのように見えるようにすることによって実現しています。ここではRRと他のモックフレームワークを比較しています:
flexmock(User).should_receive(:find).with('42').and_return(jane) # Flexmock User.should_receive(:find).with('42').and_return(jane) # Rspec User.expects(:find).with('42').returns {jane} # Mocha User.should_receive(:find).with('42') {jane} # Rspecで返値ブロックを使う場合 mock(User).find('42') {jane} # RR
RRでは「ダブルインジェクション」と知られている手法を利用しています。
my_object = MyClass.new mock(my_object).hello
これをmochaでモックを作る場合と比較します:
my_mocked_object = mock() my_mocked_object.expects(:hello)
モックオブジェクトであるという単一の目的でオブジェクトを利用するなら、空のオブジェクトを作ってそうすることができます。
mock(my_mock_object = Object.new).hello
もしくは、mock! メソッドを使うこともできます。
my_mock_object = mock!.hello.subject # Mocks the #hello method and retrieves that object via the #subject method
RRはメソッドの期待を設定するためにmethod_missingメソッドを使用します。これはshould_receiveやexpectsのようなメソッドを使う必要がないことを意味しています。
mock(my_object).hello # my_objectのhelloメソッドはモックになっています
Mocha:
my_object.expects(:hello) # expectsメソッドがhelloメソッドの期待を設定しています
Rspec mocks:
my_object.should_receive(:hello) # should_receiveがhelloメソッドの期待を設定しています
RRはmethod_missingを使用するため、ほとんどの場合において、引数の期待を設定するための#withメソッドの使用が不必要にもなっています。
mock(my_object).hello('bob', 'jane')
Mocha:
my_object.expects(:hello).with('bob', 'jane')
Rspec mocks:
my_object.should_receive(:hello).with('bob', 'jane')
RRは返値を設定するためにブロックを使うことをサポートしています。RRには#returnsメソッドもあります。両方の例は同じです。
mock(my_object).hello('bob', 'jane') {'Hello Bob and Jane'} mock(my_object).hello('bob', 'jane').returns('Hello Bob and Jane')
Mocha:
my_object.expects(:hello).with('bob', 'jane').returns('Hello Bob and Jane')
Rspec mocks:
my_object.should_receive(:hello).with('bob', 'jane').and_return('Hello Bob and Jane') my_object.should_receive(:hello).with('bob', 'jane') {'Hello Bob and Jane'} #rspecは返り値のブロックもサポートしています
あるオブジェクトのダブルを作成するには次のようなメソッドを使うことができます:
-
mock もしくは mock!
-
stub もしくは stub!
-
dont_allow もしくは dont_allow!
-
proxy もしくは proxy!
-
instance_of もしくは instance_of!
これらのメソッドは構成可能です。mock、stub、そして、dont_allowはそれらだけで使うことができて、相互排他的です。proxyとinstance_ofはmockかstubを呼び出してから使う必要があります。proxyとinstance_ofを一緒に使うこともできます。
!(びっくりマーク)が付いているメソッドはダブルの対象のオブジェクトのインスタンスを作成します。
mockはオブジェクトのメソッドを期待と実装で置き換えます。期待とは一定の引数で一定の回数(デフォルトは1回)呼び出されるモックです。メソッドが呼び出される際の返値を設定することができます。
xunitpatterns.com/Mock%20Object.html を参照して下さい。
以下の例では、viewが{:partial => “user_info”}をいう引数で1回#renderのメソッド呼び出しを受け取る期待を設定しています。メソッドが呼び出された場合、“Information”を返します。
view = controller.template mock(view).render(:partial => "user_info") {"Information"}
次のような方法でモックへ渡される引数をいくつでも許すことができます:
mock(view).render.with_any_args.twice do |*args| if args.first == {:partial => "user_info} "User Info" else "Stuff in the view #{args.inspect}" end end
stubはオブジェクトのメソッドを1つの実装で置き換えます。どのstubが実行されるのかを区別をつけるために引数と使うことができます。
xunitpatterns.com/Test%20Stub.html を参照して下さい。
以下の例では、User.find メソッドを‘42’を渡されたとき jane を返して、‘99’を渡されたとき bob を返すようにしています。もし、他の id が User.find へ渡されたとき、例外が送出されます。
jane = User.new bob = User.new stub(User).find('42') {jane} stub(User).find('99') {bob} stub(User).find do |id| raise "Unexpected id #{id.inspect} passed to me" end
dont_allow はダブルに決して呼ばれない期待を設定します。もし、ダブルが呼び出されると TimesCalledError が送出されます。
dont_allow(User).find('42') User.find('42') # TimesCalledError 例外が送出されます
mock.proxy replaces the method on the object with an expectation, implementation, and also invokes the actual method. mock.proxy also intercepts the return value and passes it into the return value block.
The following example makes sets an expectation that view.render({:partial => “right_navigation”}) gets called once and return the actual content of the rendered partial template. A call to view.render({:partial => “user_info”}) will render the user_info partial template and send the content into the block and is represented by the html variable. An assertion is done on the html and “Different html” is returned.
view = controller.template mock.proxy(view).render(:partial => "right_navigation") mock.proxy(view).render(:partial => "user_info") do |html| html.should include("John Doe") "Different html" end
You can also use mock.proxy to set expectations on the returned value. In the following example, a call to User.find(‘5’) does the normal ActiveRecord implementation and passes the actual value, represented by the variable bob, into the block. bob is then set with a mock.proxy for projects to return only the first 3 projects. bob is also mocked with valid? to return false.
mock.proxy(User).find('5') do |bob| mock.proxy(bob).projects do |projects| projects[0..3] end mock(bob).valid? {false} bob end
Intercept the return value of a method call. The following example verifies render partial will be called and renders the partial.
view = controller.template stub.proxy(view).render(:partial => "user_info") do |html| html.should include("Joe Smith") html end
Put double scenarios on instances of a Class.
mock.instance_of(User).valid? {false}
Adding a DoubleInjection to an Object + Method (done by stub, mock, or dont_allow) causes RR to record any method invocations to the Object + method. Assertions can then be made on the recorded method calls.
subject = Object.new stub(subject).foo subject.foo(1) assert_received(subject) {|subject| subject.foo(1)} assert_received(subject) {|subject| subject.bar} # This fails
subject = Object.new stub(subject).foo subject.foo(1) subject.should have_received.foo(1) subject.should have_received.bar # this fails
The block syntax has two modes
-
A normal block mode with a DoubleDefinitionCreatorProxy argument
script = MyScript.new mock(script) do |expect|
expect.system("cd #{RAILS_ENV}") {true} expect.system("rake foo:bar") {true} expect.system("rake baz") {true}
end
-
An instance_eval mode where the DoubleDefinitionCreatorProxy is instance_evaled
script = MyScript.new mock(script) do system("cd #{RAILS_ENV}") {true} system("rake foo:bar") {true} system("rake baz") {true} end
RR has a method-chaining api support for Double graphs. For example, lets say you want an object to receive a method call to #foo, and have the return value receive a method call to #bar.
In RR, you would do:
stub(object).foo.stub!.bar {:baz} object.foo.bar # :baz # or stub(object).foo {stub!.bar {:baz}} object.foo.bar # :baz # or bar = stub!.bar {:baz} stub(object).foo {bar} object.foo.bar # :baz
mock(object).foobar(1, anything) object.foobar(1, :my_symbol)
mock(object).foobar(is_a(Time)) object.foobar(Time.now)
mock(object).foobar(numeric) object.foobar(99)
mock(object).foobar(boolean) object.foobar(false)
mock(object).foobar(duck_type(:walk, :talk)) arg = Object.new def arg.walk; 'waddle'; end def arg.talk; 'quack'; end object.foobar(arg)
mock(object).foobar(1..10) object.foobar(5)
mock(object).foobar(/on/) object.foobar("ruby on rails")
mock(object).foobar(hash_including(:red => "#FF0000", :blue => "#0000FF")) object.foobar({:red => "#FF0000", :blue => "#0000FF", :green => "#00FF00"})
mock(object).foobar(satisfy {|arg| arg.length == 2}) object.foobar("xy")
Writing a custom argument wildcard matcher is not difficult. See RR::WildcardMatchers for details.
mock(object).method_name(anything).times(any_times) {return_value}
With any development effort, there are countless people who have contributed to making it possible. We all are standing on the shoulders of giants. If you have directly contributed to RR and I missed you in this list, please let me know and I will add you. Thanks!
-
Andreas Haller for patches
-
Aslak Hellesoy for Developing Rspec
-
Bryan Helmkamp for patches
-
Christopher Redinger for patches
-
Dan North for syntax ideas
-
Dave Astels for some BDD inspiration
-
Dave Myron for a bug report
-
David Chelimsky for encouragement to make the RR framework, for developing the Rspec mock framework, syntax ideas, and patches
-
Daniel Sudol for identifing performance issues with RR
-
Felix Morio for pairing with me
-
Gerard Meszaros for his excellent book “xUnit Test Patterns”
-
James Mead for developing Mocha
-
Jeff Whitmire for documentation suggestions
-
Jim Weirich for developing Flexmock, the first Terse ruby mock framework in Ruby
-
Joe Ferris for patches
-
Matthew O’Connor for patches and pairing with me
-
Michael Niessner for patches and pairing with me
-
Mike Mangino (from Elevated Rails) for patches and pairing with me
-
Myron Marston for bug reports
-
Nick Kallen for documentation suggestions, bug reports, and patches
-
Nathan Sobo for various ideas and inspiration for cleaner and more expressive code
-
Parker Thompson for pairing with me
-
Phil Darnowsky for patches
-
Pivotal Labs for sponsoring RR development
-
Stephen Baker for Developing Rspec
-
Tatsuya Ono for patches