flexmock-0.9.0/0000755000175000017500000000000011661521733013547 5ustar terceiroterceiroflexmock-0.9.0/metadata.yml0000644000175000017500000001006311661521733016052 0ustar terceiroterceiro--- !ruby/object:Gem::Specification name: flexmock version: !ruby/object:Gem::Version prerelease: version: 0.9.0 platform: ruby authors: - Jim Weirich autorequire: bindir: bin cert_chain: [] date: 2011-02-27 00:00:00 -05:00 default_executable: dependencies: [] description: "\n FlexMock is a extremely simple mock object class compatible\n with the Test::Unit framework. Although the FlexMock's\n interface is simple, it is very flexible.\n " email: jim.weirich@gmail.com executables: [] extensions: [] extra_rdoc_files: - README.rdoc - CHANGES - doc/GoogleExample.rdoc - doc/releases/flexmock-0.4.0.rdoc - doc/releases/flexmock-0.4.1.rdoc - doc/releases/flexmock-0.4.2.rdoc - doc/releases/flexmock-0.4.3.rdoc - doc/releases/flexmock-0.5.0.rdoc - doc/releases/flexmock-0.5.1.rdoc - doc/releases/flexmock-0.6.0.rdoc - doc/releases/flexmock-0.6.1.rdoc - doc/releases/flexmock-0.6.2.rdoc - doc/releases/flexmock-0.6.3.rdoc - doc/releases/flexmock-0.6.4.rdoc - doc/releases/flexmock-0.7.0.rdoc - doc/releases/flexmock-0.7.1.rdoc - doc/releases/flexmock-0.8.0.rdoc - doc/releases/flexmock-0.8.2.rdoc - doc/releases/flexmock-0.8.3.rdoc - doc/releases/flexmock-0.8.4.rdoc - doc/releases/flexmock-0.8.5.rdoc - doc/releases/flexmock-0.9.0.rdoc files: - CHANGES - Rakefile - README.rdoc - TAGS - lib/flexmock/argument_matchers.rb - lib/flexmock/argument_types.rb - lib/flexmock/base.rb - lib/flexmock/composite.rb - lib/flexmock/core.rb - lib/flexmock/core_class_methods.rb - lib/flexmock/default_framework_adapter.rb - lib/flexmock/deprecated_methods.rb - lib/flexmock/errors.rb - lib/flexmock/expectation.rb - lib/flexmock/expectation_director.rb - lib/flexmock/mock_container.rb - lib/flexmock/noop.rb - lib/flexmock/ordering.rb - lib/flexmock/partial_mock.rb - lib/flexmock/rails/view_mocking.rb - lib/flexmock/rails.rb - lib/flexmock/recorder.rb - lib/flexmock/rspec.rb - lib/flexmock/test_unit.rb - lib/flexmock/test_unit_integration.rb - lib/flexmock/undefined.rb - lib/flexmock/validators.rb - lib/flexmock/version.rb - lib/flexmock.rb - test/aliasing_test.rb - test/container_methods_test.rb - test/default_framework_adapter_test.rb - test/demeter_mocking_test.rb - test/deprecated_methods_test.rb - test/examples_from_readme_test.rb - test/extended_should_receive_test.rb - test/flexmodel_test.rb - test/naming_test.rb - test/new_instances_test.rb - test/partial_mock_test.rb - test/rails_view_stub_test.rb - test/record_mode_test.rb - test/redirect_error.rb - test/rspec_integration/integration_spec.rb - test/samples_test.rb - test/should_ignore_missing_test.rb - test/should_receive_test.rb - test/test_setup.rb - test/test_unit_integration/auto_test_unit_test.rb - test/tu_integration_test.rb - test/undefined_test.rb - flexmock.blurb - install.rb - doc/GoogleExample.rdoc - doc/releases/flexmock-0.4.0.rdoc - doc/releases/flexmock-0.4.1.rdoc - doc/releases/flexmock-0.4.2.rdoc - doc/releases/flexmock-0.4.3.rdoc - doc/releases/flexmock-0.5.0.rdoc - doc/releases/flexmock-0.5.1.rdoc - doc/releases/flexmock-0.6.0.rdoc - doc/releases/flexmock-0.6.1.rdoc - doc/releases/flexmock-0.6.2.rdoc - doc/releases/flexmock-0.6.3.rdoc - doc/releases/flexmock-0.6.4.rdoc - doc/releases/flexmock-0.7.0.rdoc - doc/releases/flexmock-0.7.1.rdoc - doc/releases/flexmock-0.8.0.rdoc - doc/releases/flexmock-0.8.2.rdoc - doc/releases/flexmock-0.8.3.rdoc - doc/releases/flexmock-0.8.4.rdoc - doc/releases/flexmock-0.8.5.rdoc - doc/releases/flexmock-0.9.0.rdoc has_rdoc: true homepage: https://github.com/jimweirich/flexmock licenses: [] post_install_message: rdoc_options: - --title - FlexMock - --main - README.rdoc - --line-numbers require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version version: "0" required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version version: "0" requirements: [] rubyforge_project: rubygems_version: 1.5.2 signing_key: specification_version: 3 summary: Simple and Flexible Mock Objects for Testing test_files: [] flexmock-0.9.0/doc/0000755000175000017500000000000011661521733014314 5ustar terceiroterceiroflexmock-0.9.0/doc/releases/0000755000175000017500000000000011661521733016117 5ustar terceiroterceiroflexmock-0.9.0/doc/releases/flexmock-0.9.0.rdoc0000644000175000017500000000514211661521733021244 0ustar terceiroterceiro= FlexMock 0.9.0 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Release 0.8.5 is a minor release with a few bug fixes. == Ruby 1.9.3 Compatibility * Fixed a number of minor warnings reported by the 1.9.3 version of Ruby. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * Easy mocking of chains of method calls. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.8.5.rdoc0000644000175000017500000000541511661521733021253 0ustar terceiroterceiro= FlexMock 0.8.5 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Release 0.8.5 is a minor release with a few bug fixes. == Bug Fixes in 0.8.5 * Fixed warning about a void context. * hsh() argument matcher now reports its matching constraints in error messages. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * Easy mocking of chains of method calls. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.8.4.rdoc0000644000175000017500000000533011661521733021246 0ustar terceiroterceiro= FlexMock 0.8.4 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Release 0.8.4 is a minor release with a few bug fixes. == Bug Fixes in 0.8.4 * The should_render_view method is now compatible with Rails 2.2.2. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * Easy mocking of chains of method calls. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.8.3.rdoc0000644000175000017500000000535711661521733021256 0ustar terceiroterceiro= FlexMock 0.8.3 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Release 0.8.3 is a minor release with a few bug fixes. == Bug Fixes in 0.8.3 * Fixed a bug where the by_default option was not completely honored in some edge cases. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * Easy mocking of chains of method calls. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.8.2.rdoc0000644000175000017500000000606611661521733021253 0ustar terceiroterceiro= FlexMock 0.8.2 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Release 0.8.2 is a minor release with a few bug fixes. == Bug Fixes in 0.8.2 * FlexMock partial mocks will now override any preexisting definitions for "should_receive". Previously, FlexMock would honor preexisting defintions, but an RSpec on Rails bug loads the RSpec mocks, even when other mock libraries are configured. This allows flexmock to correctly use partial mocks in the presence of an ill-behaved mock library. * View Stubbing has been updated to work with Rails 2.0.2. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * Easy mocking of chains of method calls. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.8.0.rdoc0000644000175000017500000000647611661521733021256 0ustar terceiroterceiro= FlexMock 0.8.0 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. It is a minor release that contains some new funtionality. == New Features in 0.8.0 * When should_ignore_missing is specified, the mock will return an undefined object for any method calls that are ignored. * A user can also specify an undefined object to be returned explicitly by using FlexMock.undefined. * Expectations may now be marked with "by_default". Default expectations will be used unless a non-default expectation is given for a matching method name. * The :respond_to? method on mocks will now accept multiple arguments. This eases the testing of models in certains situations. * An experimental view mocker method is availble to mock out views in Rails controller tests. See flexmock/rails/view_mocking.rb for more details. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * Easy mocking of chains of method calls. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.7.1.rdoc0000644000175000017500000000534311661521733021246 0ustar terceiroterceiro= FlexMock 0.7.1 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Version 0.7.1 includes a minor bug fix. == Bug Fixes n 0.7.1 * A bug in demeter mocking in 0.7.0 prevented the mocking of operators. This has been fixed. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * Easy mocking of chains of method calls. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.7.0.rdoc0000644000175000017500000001140111661521733021235 0ustar terceiroterceiro= FlexMock 0.7.0 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Version 0.7.0 introduces several enhancements. == New in 0.7.0 * FlexMock now supports the ability to mock a chain of method calls automatically. For example: car = flexmock("car", "chassis.engine.piston.stroke" => :ok) assert_equal :ok, car.chassis.engine.piston.stroke will create a sequence of mocks so that the "chassis" call will return a mock that responds to "engine", which returns a mock that responds to "piston", which returns a mock that responds to "stroke". This facility makes mocking legacy code that violates the Law of Demeter a bit easier to deal with. * Added the the +and_yield+ constraint to FlexMock expectations. This allows the user to easily specify values passed to any block given to the mock method. * Globally ordering of mocked calls is now optionally available. When a mock method is globally ordered, it must be called in the correct order with regard to all other globally ordered methods. Non-global ordering only requires that the method calls be ordered with regard to other methods on the same mock object. * The output for mock.inspect was modified to be much more consise, so that test framework error messages do not overwhelm the output. * In order to clean up the method namespace, a number of internally used methods were deprecated. All non-public methods that get added to mocks, partial mocks or test frameworks now begin with "flexmock_" (rather than "mock_"). The "mock_*" versions are still available, but will display deprecation warnings when used. The deprecated "mock_*" methods will be removed in a future version. * Additionally, the ancient "mock_handle" method has been deprecated (prints a warning when used), and will be removed in a future version. Users are encouraged to use the newer "should_receive" method instead. == New Features Added in 0.6.x In case you missed them, here are a number of features that were added during the 0.6.x versions of FlexMock. * ActiveRecord mocking support with flexmock(:model, ModelName). * Better partial mock definitions, including a "safe-mode" that minimizes mock namespace pollution in the domain object. * Support for +and_raise+ constraint to ease the definition of mocks that raise exceptions. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.6.4.rdoc0000644000175000017500000000776411661521733021261 0ustar terceiroterceiro= FlexMock 0.6.4 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Version 0.6.4 and 0.6.3 introduce several enhancements. == New in 0.6.4 (and 0.6.3) * Added the flexmock(:model, ...) method for better support when mocking ActiveRecord objects. flexmock(:model, YourModelClass) will return a pure mock object that responds to some basic ActiveRecord methods with reasonable defaults. * The flexmock() method now _always_ returns a combination domain object / mock object. This means the object return can handle domain methods and mock-specific methods (such as should_receive and mock_teardown). * A side effect of always returning a domain/mock object is that partial mocks are now enhanced with about 5 or 6 extra methods. Since partial mocks are real objects with just a few methods mocked, there is a (small) potential for a method name conflict. FlexMock now supports a safe-mode for partial mocks if this is an issue in particular case (see the RDoc README file for more details). * Fixed a small bug where attempting to mock a method that the partial mock claims to respond to, but doesn't actually have defined would cause an error. This tended to happen on active record objects where attributes are dynamically handled. NOTE: 0.6.4 improves the interface for mocking ActiveRecord model objects. The flexmodel() method was too visually similar to flexmock() and was to easy to get confused when reading code. Release 0.6.3's flexmodel() method has been removed and a new :model mode has been added to flexmock(). == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.6.3.rdoc0000644000175000017500000000741111661521733021245 0ustar terceiroterceiro= FlexMock 0.6.3 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Version 0.6.3 introduces several enhancements. == New in 0.6.3 * Added the flexmodel() method for better support when mocking ActiveRecord objects. flexmodel(YourModelClass) will return a pure mock object that responds to some basic ActiveRecord methods with reasonable defaults. The flexmodel() method is optional and you need to require 'flexmock/activerecord' to active it. * The flexmock() method now _always_ returns a combination domain object / mock object. This means the object return can handle domain methods and mock-specific methods (such as should_receive and mock_teardown). * A side effect of always returning a domain/mock object is that partial mocks are now enhanced with about 5 or 6 extra methods. Since partial mocks are real objects with just a few methods mocked, there is a (small) potential for a method name conflict. FlexMock now supports a safe-mode for partial mocks if this is an issue in particular case (see the RDoc README file for more details). * Fixed a small bug where attempting to mock a method that the partial mock claims to respond to, but doesn't actually have defined would cause an error. This tended to happen on active record objects where attributes are dynamically handled. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.6.2.rdoc0000644000175000017500000000602511661521733021244 0ustar terceiroterceiro= FlexMock 0.6.2 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Version 0.6.2 introduces a two minor enhancements. == New in 0.6.2 * When creating a partial mock using a block, flexmock() now returns the domain object rather than the mock proxy. This allows the following to work: obj = flexmock(Something.new) { |m| m.should_receive(:hi).once } obj.hi See http://onestepback.org/index.cgi/Tech/Ruby/FlexMockReturns.red for more details. * The +and_raise+ method is now supported for directly specifying that exceptions will be thrown from a mock. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.6.1.rdoc0000644000175000017500000000527211661521733021246 0ustar terceiroterceiro= FlexMock 0.6.1 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Version 0.6.1 introduces a number minor bug fixes. == New in 0.6.1 * Fixed several bugs related to partial mocks and ordering and mocking field assignments. == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.6.0.rdoc0000755000175000017500000001075711661521733021254 0ustar terceiroterceiro= FlexMock 0.6.0 Released FlexMock is a flexible mocking library for use in unit testing and behavior specification in Ruby. Version 0.6.0 introduces a number of API enhancements to make testing with mocks even easier than before. == New in 0.6.0 * Better integration with Test::Unit (no need to explicitly include FlexMock::TestCase). * Integration with RSpec (version 0.9.0 or later of RSpec is required). * The +flexmock+ method will now create both regular mocks and partial mocks. flexmock() # => a full mock flexmock(person) # => a partial mock based on person (+flexstub+ is still included for backwards compatibility). * Quick and simple mocks my now be created using an expectation hash. For example: flexmock(:foo => 10, :bar => "Hello") will create a mock with two methods, :foo and :bar,defined. :foo will return 10 when invoked, and :bar will return "Hello". * The +should_receive+ method will now allow multiple methods (with the same constraints) be defined in a single call. For example, the following declares that both :read and :write need to be called at least one time each on the mock object. flexmock.should_receive(:read, :write).at_least.once * +should_receive+ now will allow expectation hashes as arguments. This is similar to the list of methods, but allows each defined method to have its own return value. flexmock.should_receive(:name => "John", :age => 32) * In addition to using a block for defining constrains, constraints may now be applied directly to the return value of +new_instances+. Combined with the expectation hashes supported by +should_receive+, simple mocking scenarios have become much more succinct. For example: flexmock(Person).new_instances.should_receive(:name => "John", :age => 32) * Improved implementation, allowing for more flexible use and greater consistency between full mock and partial mocks. * Version 0.6.0 also includes a fix for an incompatibility with some older versions of RCov. The FlexMock Rakefile now includes a RCov task (and we have 100% code coverage). == What is FlexMock? FlexMock is a flexible framework for creating mock object for testing. When running unit tests, it is often desirable to use isolate the objects being tested from the "real world" by having them interact with simplified test objects. Sometimes these test objects simply return values when called, other times they verify that certain methods were called with particular arguments in a particular order. FlexMock makes creating these test objects easy. === Features * Easy integration with both Test::Unit and RSpec. Mocks created with the flexmock method are automatically verified at the end of the test or example. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. * The ability to cause classes to instantiate test instances (instead of real instances) for the duration of a test. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://flexmock.rubyforge.org for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://flexmock.rubyforge.org. -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.5.1.rdoc0000644000175000017500000000435311661521733021244 0ustar terceiroterceiro= FlexMock 0.5.0 Released FlexMock is a flexible mocking library for use in Ruby's Test::Unit test framework. Version 0.5.1 is a minor bug fix release. == New in 0.5.1 * Version 0.5.1 fixes a problem that caused some older versions of RCov to core dump. == What is FlexMock? FlexMock is a flexible Ruby mocking library that works with Ruby's Test::Unit framework to create easy to use mocks. === Features * Easy integration with Test::Unit. Mocks created with the flexmock method are automatically verified at the end of the test. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock' class TestDog < Test::Unit::TestCase include FlexMock::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://onestepback.org/software/flexmock for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://onestepback.org/software/flexmock/ -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.5.0.rdoc0000755000175000017500000000565111661521733021250 0ustar terceiroterceiro= FlexMock 0.5.0 Released FlexMock is a flexible mocking library for use in Ruby's Test::Unit test framework. Version 0.5.0 adds the ability to automatically stub any instance created by an existing class. == New in 0.5.0 * flexstub(obj) will now accept a block argument in the same way that flexmock() does. * When stubbing Class objects, the any_instance method can be used to automatically stub any instance object created by the class. For example, if you wish that any Connection object created during a test has a stubbed "send" method, you could do the following: def test_connections flexstub(Connection).any_instance do |new_con| new_con.should_receive(:send).and_return(0) end connection = Connection.new connection.send # This calls the stubbed version of send. end Only objects created during the test will be automatically stubbed. Existing objects are unaffected. == What is FlexMock? FlexMock is a flexible Ruby mocking library that works with Ruby's Test::Unit framework to create easy to use mocks. === Features * Easy integration with Test::Unit. Mocks created with the flexmock method are automatically verified at the end of the test. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock' class TestDog < Test::Unit::TestCase include FlexMock::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://onestepback.org/software/flexmock for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability You can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://onestepback.org/software/flexmock/ -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.4.3.rdoc0000644000175000017500000000453011661521733021242 0ustar terceiroterceiro= FlexMock 0.4.3 Released FlexMock is a flexible mocking library for use in Ruby's Test::Unit test framework. Version 0.4.0 enhances FlexMock with the ability to stub and mock methods in existing objects. == New in 0.4.3 Release 0.4.3 contains a fix for handling non-direct class methods properly (bug report from Scott Barron). == What is FlexMock? FlexMock is a flexible Ruby mocking library that works with Ruby's Test::Unit framework to create easy to use mocks. === Features * Easy integration with Test::Unit. Mocks created with the flexmock method are automatically verified at the end of the test. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock' class TestDog < Test::Unit::TestCase include FlexMock::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://onestepback.org/software/flexmock for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability FlexMock is distributed with Rails, or you can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://onestepback.org/software/flexmock/ -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.4.2.rdoc0000644000175000017500000000455611661521733021251 0ustar terceiroterceiro= FlexMock 0.4.2 Released FlexMock is a flexible mocking library for use in Ruby's Test::Unit test framework. Version 0.4.0 enhances FlexMock with the ability to stub and mock methods in existing objects. == New in 0.4.2 Release 0.4.2 contains a fix for multiple definitions of a class method stub so that the correct original definition is retained. == What is FlexMock? FlexMock is a flexible Ruby mocking library that works with Ruby's Test::Unit framework to create easy to use mocks. === Features * Easy integration with Test::Unit. Mocks created with the flexmock method are automatically verified at the end of the test. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock' class TestDog < Test::Unit::TestCase include FlexMock::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://onestepback.org/software/flexmock for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability FlexMock is distributed with Rails, or you can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://onestepback.org/software/flexmock/ -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.4.1.rdoc0000644000175000017500000000457011661521733021244 0ustar terceiroterceiro= FlexMock 0.4.1 Released FlexMock is a flexible mocking library for use in Ruby's Test::Unit test framework. Version 0.4.0 enhances FlexMock with the ability to stub and mock methods in existing objects. == New in 0.4.1 Coming fast on the heels of 0.4.0, version 0.4.1 fixes a problem with mocking methods that have the same name as methods defined in Kernel. == What is FlexMock? FlexMock is a flexible Ruby mocking library that works with Ruby's Test::Unit framework to create easy to use mocks. === Features * Easy integration with Test::Unit. Mocks created with the flexmock method are automatically verified at the end of the test. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock' class TestDog < Test::Unit::TestCase include FlexMock::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://onestepback.org/software/flexmock for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability FlexMock is distributed with Rails, or you can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://onestepback.org/software/flexmock/ -- Jim Weirich flexmock-0.9.0/doc/releases/flexmock-0.4.0.rdoc0000644000175000017500000000554411661521733021245 0ustar terceiroterceiro= FlexMock 0.4.0 Released FlexMock is a flexible mocking library for use in Ruby's Test::Unit test framework. Version 0.4.0 enhances FlexMock with the ability to stub and mock methods in existing objects. == Changes === New Features in 0.4.0 * You can now use the flexstub(object) method to mock or stub individual methods in an existing object. The original definitions of the methods are restored at the end of a test. * The and_return (and its alias, returns) now accepts a list of arguments and will return the values in the list one at a time for each successive call to the mocked method. * The flexmock() method now accepts an initialization block so that a mock can be created and configured in one step without using a local variable. This is really handy when mocking factory or creation methods that in turn return a mock. == What is FlexMock? FlexMock is a flexible Ruby mocking library that works with Ruby's Test::Unit framework to create easy to use mocks. === Features * Easy integration with Test::Unit. Mocks created with the flexmock method are automatically verified at the end of the test. * A fluent interface that allows mock behavior to be specified very easily. * A "record mode" where an existing implementation can record its interaction with a mock for later validation against a new implementation. * Easy mocking of individual methods in existing, non-mock objects. === Example Suppose you had a Dog object that wagged a tail when it was happy. Something like this: class Dog def initialize(a_tail) @tail = a_tail end def happy @tail.wag end end To test the +Dog+ class without a real +Tail+ object (perhaps because real +Tail+ objects activate servos in some robotic equipment), you can do something like this: require 'test/unit' require 'flexmock' class TestDog < Test::Unit::TestCase include FlexMock::TestCase def test_dog_wags_tail_when_happy tail = flexmock("tail") tail.should_receive(:wag).once dog = Dog.new(tail) dog.happy end end FlexMock will automatically verify that the mocked tail object received the message +wag+ exactly one time. If it doesn't, the test will not pass. See the FlexMock documentation at http://onestepback.org/software/flexmock for details on specifying arguments and return values on mocked methods, as well as a simple technique for mocking tail objects when the Dog class creates the tail objects directly. == Availability FlexMock is distributed with Rails, or you can make sure you have the latest version with a quick RubyGems command: gem install flexmock (you may need root/admin privileges) Otherwise, you can get it from the more traditional places: Download:: http://rubyforge.org/project/showfiles.php?group_id=170 You will find documentation at: http://onestepback.org/software/flexmock/ -- Jim Weirich flexmock-0.9.0/doc/GoogleExample.rdoc0000755000175000017500000002731211661521733017725 0ustar terceiroterceiro= Extended FlexMock Example Using Google4R Google4R is a simple Ruby wrapper around the Google APIs. In this extended example, we will use FlexMock to test software that uses the Google APIs, without every communicating with Google itself. == Purchase.rb Here is the bit of code that we will be testing... require 'google4r/checkout' require 'item' class Purchase def initialize(config) @frontend = Frontend.new(config) @frontend.tax_table_factory = TaxTableFactory.new end # Purchase the +quantity+ items identified by +item_id+. Return the # confirmation page URL. def purchase(item_id, quantity=1) item = Item.find(item_id) checkout = @frontend.create_checkout_command checkout.cart.create_item do |cart_item| cart_item.name = item.name cart_item.description = item.description cart_item.unit_price = item.unit_price cart_item.quantity = quantity end response = checkout.send_to_google_checkout response.redirect_url end end +FrontEnd+ is a Google4R class that provides a lot of the front end work for talking to the Google APIs. The config object given to the Purchase initializer is simply a hash of values defining the merchant_id, merchant_key and sandbox flag. To use the real Google checkout APIs, you will need to obtains a merchant id and key from Google. Since we will be mocking the Google interaction, we can use dummy values in our test. The tax table factory is required by the Google4R software. We provide the following simplified one. Read the Google API documents for more information. class TestTaxTableFactory def effective_tax_tables_at(time) tax_free_table = TaxTable.new(false) tax_free_table.name = "default table" tax_free_table.create_rule do |rule| rule.area = UsCountryArea.new(UsCountryArea::ALL) rule.rate = 0.0 end return [tax_free_table] end end +Item+ is simply an ActiveRecord class that we are using to hold our purchase item information. It should respond to the +name+, +description+ and +unit_price+ messages. == Testing Without Using External Resources Our first test attempt will be to run the +purchase+ method without talking to either the live Google web services, or hitting an actual ActiveRecord database. === Mocking Active Record The ActiveRecord part is easy to mock. The following will handle it: flexmock(Item).should_receive(:find).with(1).and_return( flexmock("guitar", :name => "Deschutes", :description => "Deschutes model Guitar", :unit_price => Money.new(2400.00))) We have mocked out the +find+ method on +Item+ so that whenever we call find with an integer argument of 1, we will return a mock item that will report its name, description and unit_price. This gives us an item for testing without actually reading the database. === Mocking the Google Web Services Call Next we want to prevent the Google4R API from actually talking to the live web service. Everything that happens in the purchase method is all done locally except for the final call to +send_to_google_checkout+. All we need to do is mock out that one method. flexmock(Google4R::Checkout::CheckoutCommand).new_instances do |instance| instance.should_receive(:send_to_google_checkout).once. and_return(flexmock(:redirect_url => "http://google.response.url")) end When we ask +FrontEnd+ to create a check out command, it returns an instance of Google4R::Checkout::CheckoutCommand. We then use flexmock to specify that when Google4R::Checkout::CheckoutCommand creates a new instance, it should actually return a partial mock of that instance. The block given to the +new_instances+ method allows us to configure the mocked checkout command. We tell it return a response object (yes, another mock) that report our dummy response URL. === The Final Result Here is the complete unit test: def test_buying_a_guitar # Setup flexmock(Item).should_receive(:find).with(1).and_return( flexmock("guitar", :name => "Deschutes", :description => "Deschutes model Guitar", :unit_price => Money.new(2400.00))) flexmock(Google4R::Checkout::CheckoutCommand).new_instances do |instance| instance.should_receive(:send_to_google_checkout).once. and_return(flexmock(:redirect_url => "http://google.response.url")) end # Execute p = Purchase.new({ :merchant_id => 'dummy_id', :merchant_key => 'dummy_key', :use_sandbox => true }) url = p.purchase(1) # Assert assert_equal "http://google.response.url", url end == Testing the Details The above test is fine as far as it goes. It demonstrates how to use mocks to avoid talking to external resources such as databases and web services. But as a unit test, it is sorely lacking in several areas. All the test really demonstrates is that the +send_to_google_checkout+ method is called. There are no tests to ensure that the right item descriptions and prices are correctly stored in the cart. In fact, if we rewrote the purchase method as follows: def purchase(item_id, quantity=1) @frontend.create_checkout_command.send_to_google_checkout.redirect_url end it would still pass the unit test we designed, even though the rewrite is obviously an incorrect implementation. A more complete test is a bit more complicated. Here are the details. === Mocking Active Record Our incorrect version of purchase never calls the +find+ method of Item. We can easily test for that by adding a +once+ constraint one that mock specification. Since find is a read-only method, we don't really care if it is called multiple times, as long as it is called at least one time, so we will add an +at_least+ modifier as well. Finally, we are going to break the guitar mock out into its own declaration. The reason will become obvious in a bit. mock_guitar = flexmock("guitar", :name => "Deschutes", :description => "Deschutes model guitar", :unit_price => Money.new(2400.00)) flexmock(Item).should_receive(:find).with(1).at_least.once. and_return(mock_guitar) === Mocking a Cart Item The next bit is a wee bit complicated, but we will handle it a little bit at a time so that it doesn't become overwhelming. There are three main objects in the Google checkout API that we deal with in the next section.: (1) the checkout command object returned by the front end, (2) the cart object returned by the checkout command, and (3) the item passed to the block in the +create_item+ call. We will tackle them in reverse order, starting with the item objects given to the +create_item+ block. The item must respond to four attribute assignments. This is straightforward to mock, just make sure you include the +once+ constraint so that the assignments are required. mock_item = flexmock("item") mock_item.should_receive(:name=).with(mock_guitar.name).once mock_item.should_receive(:description=).with(mock_guitar.description).once mock_item.should_receive(:unit_price=).with(mock_guitar.unit_price).once mock_item.should_receive(:quantity=).with(1).once Notice how we used the mock_guitar object defined earlier to provide values in the +with+ constraint. This way we don't have to repeat the explicit strings and values we are checking. (Keep it DRY!). === Mocking the Cart The mock cart object will pass the mock_item to a block when the +create_item+ method is called. We specify that with the following: mock_cart = flexmock("cart") mock_cart.should_receive(:create_item).with(Proc).once.and_return { |block| block.call(mock_item) } FlexMock objects can handle blocks passed to them by treating them as the final object in the calling list. Use +Proc+ in the +with+ constraint to match the block and then invoke the block explicitly via block.call(...) in the +and_return+ specification. === Mocking the Checkout Command Finally, we tie it all together by mocking the checkout command. As before, we use +new_instances+ to force newly created checkout commands to be stubbed. This time we not only mockout the +send_to_google+ method, but we also mock the +cart+ command to return the carefully crafted +mock_cart+ object from the previous section. flexmock(Google4R::Checkout::CheckoutCommand).new_instances do |instance| instance.should_receive(:cart).with().once.and_return(mock_cart) instance.should_receive(:send_to_google_checkout).once. and_return(flexmock(:redirect_url => "http://google.response.url")) end === The Final Test Method Here is the complete detailed version of the test method. def test_buying_a_guitar_with_details # Setup mock_guitar = flexmock("guitar", :name => "Deschutes", :description => "Deschutes model guitar", :unit_price => Money.new(2400.00)) flexmock(Item).should_receive(:find).with(1).at_least.once. and_return(mock_guitar) mock_item = flexmock("item") mock_item.should_receive(:name=).with(mock_guitar.name).once mock_item.should_receive(:description=).with(mock_guitar.description).once mock_item.should_receive(:unit_price=).with(mock_guitar.unit_price).once mock_item.should_receive(:quantity=).with(1).once mock_cart = flexmock("cart") mock_cart.should_receive(:create_item).with(Proc).once.and_return { |block| block.call(mock_item) } flexmock(Google4R::Checkout::CheckoutCommand).new_instances do |instance| instance.should_receive(:cart).with().once.and_return(mock_cart) instance.should_receive(:send_to_google_checkout).once. and_return(flexmock(:redirect_url => "http://google.response.url")) end # Execute p = Purchase.new({ :merchant_id => 'dummy_id', :merchant_key => 'dummy_key', :use_sandbox => true }) url = p.purchase(1) # Assert assert_equal "http://google.response.url", url end == Summary Testing with mock objects can get complex. We used seven different mock or partial mock objects in testing the interaction of our code with the Google checkout API. Most testing scenarios won't require that many, but anytime your code touches something external, it might require a mock object for testing. We should stop and ask ourselves: was it worth it? It seems like an awful lot of work just to test a very simple purchase method. Wouldn't it just be easier to just use the Google API directly for testing and forget about the mocks? Perhaps, but using mock objects have several definite advantages: * You can run the test at any time without worrying whether Google, the internet, or anything else is up and connected. * You can easy test for error conditions using mock objects. For example, does your code correctly handle the case where you get an exception when connecting to google? Mocks can easily create those error conditions that are difficult to achieve with real objects. E.g. instance.should_receive(:send_to_google_checkout).once. and_return { raise Google4R::Checkout::GoogleCheckoutError } Some might point out that in the final test method we are hardly using Google4R software at all, most of the code we interact with are mock objects. Doesn't that defeat the purpose of testing? The answer is simple. Always keep in mind what you are testing. The goal of the TestPurchase test case is not the make sure the Google4R code is correct, but that our Purchase class correctly interoperates with it. We do that by carefully stating what methods are called with what arguments and what they return. The test just checks that we are using to external software as we expect it to. We don't actually care about the Google4R software itself in this test case (presumably we do have tests that cover Google4R, but those are different tests). In the end, mock objects are a power tool to have in your testing toolbox.flexmock-0.9.0/install.rb0000644000175000017500000000170011661521733015540 0ustar terceiroterceirorequire 'rbconfig' require 'find' require 'ftools' include Config def indir(newdir) olddir = Dir.pwd Dir.chdir(newdir) yield ensure Dir.chdir(olddir) end $ruby = CONFIG['ruby_install_name'] $sitedir = CONFIG["sitelibdir"] unless $sitedir version = CONFIG["MAJOR"]+"."+CONFIG["MINOR"] $libdir = File.join(CONFIG["libdir"], "ruby", version) $sitedir = $:.find {|x| x =~ /site_ruby/} if !$sitedir $sitedir = File.join($libdir, "site_ruby") elsif $sitedir !~ Regexp.quote(version) $sitedir = File.join($sitedir, version) end end if (destdir = ENV['DESTDIR']) $sitedir = destdir + $sitedir File::makedirs($sitedir) end flexmock_dest = File.join($sitedir, "flexmock") File::makedirs(flexmock_dest, true) File::chmod(0755, flexmock_dest) # The library files file = 'flexmock.rb' indir('lib') do Dir['**/*.rb'].each do |file| File::install( file, File.join($sitedir, file), 0644, true) end end flexmock-0.9.0/flexmock.blurb0000644000175000017500000000077111661521733016414 0ustar terceiroterceironame: flexmock document: http://onestepback.org/software/flexmock download: http://onestepback.org/packages/flexmock description: >

FlexMock is the outcome of a frustrating evening of trying to use the original mock object by Nat Pryce. Nat's mock object is really cool, but it assumes that we know the exact calling order of all the methods to the mock object. I really feel that over-constrains the solution code. This little quicky seems to meet my needs fairly well.

flexmock-0.9.0/test/0000755000175000017500000000000011661521733014526 5ustar terceiroterceiroflexmock-0.9.0/test/undefined_test.rb0000644000175000017500000000405411661521733020056 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require "test/test_setup" class UndefinedTest < Test::Unit::TestCase def test_undefined_method_calls_return_undefined assert_undefined undefined.some_random_undefined_method end def test_equals assert undefined == undefined assert ! (undefined == Object.new) end def test_math_operators assert_undefined undefined + 1 assert_undefined undefined - 1 assert_undefined undefined * 1 assert_undefined undefined / 1 assert_undefined undefined ** 1 end def test_math_operators_reversed assert_undefined 1 + undefined assert_undefined 1 - undefined assert_undefined 1 * undefined assert_undefined 1 / undefined assert_undefined 2 ** undefined end def test_comparisons assert_undefined undefined < 1 assert_undefined undefined <= 1 assert_undefined undefined > 1 assert_undefined undefined >= 1 assert_undefined undefined <=> 1 end def test_comparisons_reversed assert_undefined 1 < undefined assert_undefined 1 <= undefined assert_undefined 1 > undefined assert_undefined 1 >= undefined assert_undefined 1 <=> undefined end def test_base_level_methods assert_kind_of FlexMock::Undefined, undefined end def test_cant_create_a_new_undefined assert_raises(NoMethodError) do FlexMock::Undefined.new end end def test_cant_clone_undefined assert_undefined undefined.clone assert_equal undefined.__id__, undefined.clone.__id__ end def test_string_representations assert_equal "-UNDEFINED-", undefined.to_s assert_equal "-UNDEFINED-", undefined.inspect end def test_undefined_is_not_nil assert ! undefined.nil? end private def assert_undefined(obj) assert undefined == obj end def undefined FlexMock.undefined end end flexmock-0.9.0/test/tu_integration_test.rb0000644000175000017500000000466011661521733021153 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' # The following tests exercise Test::Unit integration. They are # disabled if actually running under MiniTest because the MiniTest is # different enough internally that the tests are not worthwhile. unless defined?(MiniTest) class TestTuIntegrationFlexMockMethod < Test::Unit::TestCase include FlexMock::TestCase def test_can_construct_flexmock mock = flexmock("x") mock.should_receive(:hi).and_return(:hello) assert_equal :hello, mock.hi end def test_can_construct_flexmock_with_block mock = flexmock("x") do |m| m.should_receive(:hi).and_return(:hello) end assert_equal :hello, mock.hi end end class TestTuIntegrationMockVerificationInTeardown < Test::Unit::TestCase include FlexMock::TestCase def teardown assert_raise(assertion_failed_error) do super end end def test_mock_verification_occurs_during_teardown flexmock("xyz").should_receive(:hi).with(any).once end end class TestTuIntegrationMockVerificationWithoutSetup < Test::Unit::TestCase include FlexMock::TestCase def teardown assert_raise(assertion_failed_error) do super end end def test_mock_verification_occurs_during_teardown flexmock("xyz").should_receive(:hi).with(any).once end end class TestTuIntegrationMockVerificationForgetfulSetup < Test::Unit::TestCase include FlexMock::TestCase def teardown assert_raise(assertion_failed_error) do super end end def test_mock_verification_occurs_during_teardown flexmock("xyz").should_receive(:hi).with(any).once end end class TestTuIntegrationSetupOverridenAndNoMocksOk < Test::Unit::TestCase include FlexMock::TestCase def test_mock_verification_occurs_during_teardown end end class TestTuIntegrationFailurePreventsVerification < Test::Unit::TestCase include FlexMock::TestCase def test_mock_verification_occurs_during_teardown flexmock('m').should_receive(:hi).once simulate_failure end private def simulate_failure @test_passed = false end end end flexmock-0.9.0/test/test_unit_integration/0000755000175000017500000000000011661521733021147 5ustar terceiroterceiroflexmock-0.9.0/test/test_unit_integration/auto_test_unit_test.rb0000755000175000017500000000134411661521733025606 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require "test/test_setup" require "flexmock/base" require "flexmock/test_unit" class TestFlexmockTestUnit < Test::Unit::TestCase def teardown super end # This test should pass. def test_can_create_mocks m = flexmock("mock") m.should_receive(:hi).once m.hi end # This test should fail during teardown. def test_should_fail__mocks_are_auto_verified m = flexmock("mock") m.should_receive(:hi).once end end flexmock-0.9.0/test/test_setup.rb0000644000175000017500000000135411661521733017255 0ustar terceiroterceirorequire 'test/unit' require 'fileutils' require 'flexmock' require 'test/redirect_error' class FlexMock module TestCase def assertion_failed_error FlexMock.framework_adapter.assertion_failed_error end # Assertion helper used to assert validation failure. If a # message is given, then the error message should match the # expected error message. def assert_failure(message=nil) ex = assert_raises(assertion_failed_error) { yield } if message case message when Regexp assert_match message, ex.message when String assert ex.message.index(message), "Error message '#{ex.message}' should contain '#{message}'" end end ex end end end flexmock-0.9.0/test/should_receive_test.rb0000644000175000017500000006747311661521733021133 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' def mock_top_level_function :mtlf end module Kernel def mock_kernel_function :mkf end end # Used for testing class Cat def purr end def meow end end class TestFlexMockShoulds < Test::Unit::TestCase include FlexMock::TestCase # Expected error messages on failures COUNT_ERROR_MESSAGE = /\bcalled\s+incorrect\s+number\s+of\s+times\b/ NO_MATCH_ERROR_MESSAGE = /\bno\s+matching\s+handler\b/ AT_LEAST_ERROR_MESSAGE = /\bshould\s+be\s+called\s+at\s+least\b/ AT_MOST_ERROR_MESSAGE = /\bshould\s+be\s+called\s+at\s+most\b/ OUT_OF_ORDER_ERROR_MESSAGE = /\bcalled\s+out\s+of\s+order\b/ NON_CONTAINER_MESSAGE = /\bis\s+not\s+in\s+a\s+container\b/ def test_defaults FlexMock.use do |m| m.should_receive(:hi) assert_nil m.hi assert_nil m.hi(1) assert_nil m.hi("hello", 2) end end def test_returns_with_value FlexMock.use do |m| m.should_receive(:hi).returns(1) assert_equal 1, m.hi assert_equal 1, m.hi(123) end end def test_returns_with_multiple_values FlexMock.use do |m| m.should_receive(:hi).and_return(1,2,3) assert_equal 1, m.hi assert_equal 2, m.hi assert_equal 3, m.hi assert_equal 3, m.hi assert_equal 3, m.hi end end def test_multiple_returns FlexMock.use do |m| m.should_receive(:hi).and_return(1).and_return(2,3) assert_equal 1, m.hi assert_equal 2, m.hi assert_equal 3, m.hi assert_equal 3, m.hi assert_equal 3, m.hi end end def test_returns_with_block FlexMock.use do |m| result = nil m.should_receive(:hi).with(Object).returns { |obj| result = obj } m.hi(3) assert_equal 3, result end end def test_block_example_from_readme FlexMock.use do |m| m.should_receive(:foo).with(Integer,Proc).and_return(:got_block) m.should_receive(:foo).with(Integer).and_return(:no_block) assert_equal :no_block, m.foo(1) assert_equal :got_block, m.foo(1) { } end end def test_return_with_and_without_block_interleaved FlexMock.use do |m| m.should_receive(:hi).and_return(:a).and_return { :b }.and_return(:c) assert_equal :a, m.hi assert_equal :b, m.hi assert_equal :c, m.hi assert_equal :c, m.hi end end def test_and_returns_alias FlexMock.use do |m| m.should_receive(:hi).and_return(4) assert_equal 4, m.hi end end def test_and_return_undefined FlexMock.use do |m| m.should_receive(:foo).and_return_undefined m.should_receive(:phoo).returns_undefined assert_equal FlexMock.undefined, m.foo assert_equal FlexMock.undefined, m.foo.bar.baz.bing.ka_ching assert_equal FlexMock.undefined, m.phoo.bar.baz.bing.ka_ching end end def test_and_yield_will_continue_to_yield_the_same_value FlexMock.use do |m| m.should_receive(:hi).and_yield(:yield_value) assert_equal :yield_value, m.hi { |v| v } assert_equal :yield_value, m.hi { |v| v } end end def test_and_yield_with_multiple_values_yields_the_values FlexMock.use do |m| m.should_receive(:hi).and_yield(:one, :two).once assert_equal [:one, :two], m.hi { |a, b| [a, b] } end end def test_multiple_yields_are_done_sequentially FlexMock.use do |m| m.should_receive(:msg).and_yield(:one).and_yield(:two) assert_equal :one, m.msg { |a| a } assert_equal :two, m.msg { |a| a } assert_equal :two, m.msg { |a| a } end end def test_failure_if_no_block_given FlexMock.use do |m| m.should_receive(:hi).and_yield(:one, :two).once assert_raise(FlexMock::MockError) do m.hi end end end def test_failure_different_return_value_than_yield_return FlexMock.use do |m| m.should_receive(:hi).and_yield(:yld).once.and_return(:ret) yielded_value = nil assert_equal :ret, m.hi { |v| yielded_value = v } assert_equal :yld, yielded_value end end def test_multiple_yields FlexMock.use do |m| m.should_receive(:hi).and_yield(:one, :two).and_yield(1, 2) assert_equal [:one, :two], m.hi { |a, b| [a, b] } assert_equal [1, 2], m.hi { |a, b| [a, b] } end end def test_multiple_yields_will_yield_the_last_value_set FlexMock.use do |m| m.should_receive(:hi).and_yield(:a).and_yield(:b) assert_equal [:a], m.hi { |a, b| [a] } assert_equal [:b], m.hi { |a, b| [a] } assert_equal [:b], m.hi { |a, b| [a] } assert_equal [:b], m.hi { |a, b| [a] } assert_equal [:b], m.hi { |a, b| [a] } end end def test_yielding_then_not_yielding_and_then_yielding_again FlexMock.use do |m| m.should_receive(:hi).and_yield(:a).once m.should_receive(:hi).and_return(:b).once m.should_receive(:hi).and_yield(:c).once assert_equal :a, m.hi { |v| v } assert_equal :b, m.hi assert_equal :c, m.hi { |v| v } end end def test_yields_syntax FlexMock.use do |m| m.should_receive(:hi).yields(:one) assert_equal :one, m.hi { |a| a } end end class MyError < RuntimeError end def test_and_raises_with_exception_class_throws_exception FlexMock.use do |m| m.should_receive(:failure).and_raise(MyError) assert_raise MyError do m.failure end end end def test_and_raises_with_arguments_throws_exception_made_with_args FlexMock.use do |m| m.should_receive(:failure).and_raise(MyError, "my message") ex = assert_raise MyError do m.failure end assert_equal "my message", ex.message end end def test_and_raises_with_a_specific_exception_throws_the_exception FlexMock.use do |m| err = MyError.new m.should_receive(:failure).and_raise(err) ex = assert_raise MyError do m.failure end assert_equal err, ex end end def test_raises_is_an_alias_for_and_raise FlexMock.use do |m| m.should_receive(:failure).raises(RuntimeError) assert_raise RuntimeError do m.failure end end end def test_multiple_and_raise_clauses_will_be_done_sequentially FlexMock.use do |m| m.should_receive(:failure). and_raise(RuntimeError, "ONE"). and_raise(RuntimeError, "TWO") ex = assert_raise RuntimeError do m.failure end assert_equal "ONE", ex.message ex = assert_raise RuntimeError do m.failure end assert_equal "TWO", ex.message end end def test_and_throw_will_throw_a_symbol FlexMock.use do |m| m.should_receive(:msg).and_throw(:sym) value = catch(:sym) do m.msg fail "Should not reach this line" end assert_nil value end end def test_and_throw_with_expression_will_throw FlexMock.use do |m| m.should_receive(:msg).and_throw(:sym, :return_value) value = catch(:sym) do m.msg fail "Should not reach this line" end assert_equal :return_value, value end end def test_throws_is_an_alias_for_and_throw FlexMock.use do |m| m.should_receive(:msg).throws(:sym, :return_value) value = catch(:sym) do m.msg fail "Should not reach this line" end assert_equal :return_value, value end end def test_multiple_throws_will_be_done_sequentially FlexMock.use do |m| m.should_receive(:toss). and_throw(:sym, "ONE"). and_throw(:sym, "TWO") value = catch(:sym) do m.toss end assert_equal "ONE", value value = catch(:sym) do m.toss end assert_equal "TWO", value end end def test_multiple_expectations FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10) m.should_receive(:hi).with(2).returns(20) assert_equal 10, m.hi(1) assert_equal 20, m.hi(2) end end def test_with_no_args_with_no_args FlexMock.use do |m| m.should_receive(:hi).with_no_args m.hi end end def test_with_no_args_but_with_args assert_failure(NO_MATCH_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with_no_args m.hi(1) end end end def test_with_any_args FlexMock.use do |m| m.should_receive(:hi).with_any_args m.hi m.hi(1) m.hi(1,2,3) m.hi("this is a test") end end def test_with_any_single_arg_matching FlexMock.use('greeter') do |m| m.should_receive(:hi).with(1,FlexMock.any).twice m.hi(1,2) m.hi(1, "this is a test") end end def test_with_any_single_arg_nonmatching FlexMock.use('greeter') do |m| m.should_receive(:hi).times(3) m.should_receive(:hi).with(1,FlexMock.any).never m.hi m.hi(1) m.hi(1, "hi", nil) end end def test_with_equal_arg_matching FlexMock.use('greeter') do |m| m.should_receive(:hi).with(FlexMock.eq(Object)).once m.hi(Object) end end def test_with_ducktype_arg_matching FlexMock.use('greeter') do |m| m.should_receive(:hi).with(FlexMock.ducktype(:purr, :meow)).once m.hi(Cat.new) end end def test_with_ducktype_arg_matching_no_match FlexMock.use('greeter') do |m| m.should_receive(:hi).with(FlexMock.ducktype(:purr, :meow, :growl)) assert_failure { m.hi(Cat.new) } end end def test_with_hash_matching FlexMock.use('greeter') do |m| m.should_receive(:hi).with(FlexMock.hsh(:a => 1, :b => 2)).once m.hi(:a => 1, :b => 2, :c => 3) end end def test_with_hash_non_matching FlexMock.use('greeter') do |m| m.should_receive(:hi).with(FlexMock.hsh(:a => 1, :b => 2)) assert_failure { m.hi(:a => 1, :b => 4, :c => 3) } end end def test_with_equal_arg_nonmatching FlexMock.use('greeter') do |m| m.should_receive(:hi).with(FlexMock.eq(Object)).never m.should_receive(:hi).never m.should_receive(:hi).with(1).once m.hi(1) end end def test_with_arbitrary_arg_matching FlexMock.use('greeter') do |m| m.should_receive(:hi).with(FlexMock.on { |arg| arg % 2 == 0 }).twice m.should_receive(:hi).never m.should_receive(:hi).with(1).once m.should_receive(:hi).with(2).never m.should_receive(:hi).with(3).once m.should_receive(:hi).with(4).never m.hi(1) m.hi(2) m.hi(3) m.hi(4) end end def test_args_matching_with_regex FlexMock.use do |m| m.should_receive(:hi).with(/one/).returns(10) m.should_receive(:hi).with(/t/).returns(20) assert_equal 10, m.hi("one") assert_equal 10, m.hi("done") assert_equal 20, m.hi("two") assert_equal 20, m.hi("three") end end def test_arg_matching_with_regex_matching_non_string FlexMock.use do |m| m.should_receive(:hi).with(/1/).returns(10) assert_equal 10, m.hi(319) end end def test_arg_matching_with_class FlexMock.use do |m| m.should_receive(:hi).with(Fixnum).returns(10) m.should_receive(:hi).with(Object).returns(20) assert_equal 10, m.hi(319) assert_equal 10, m.hi(Fixnum) assert_equal 20, m.hi("hi") end end def test_arg_matching_with_no_match FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10) assert_failure(NO_MATCH_ERROR_MESSAGE) { assert_equal 20, m.hi(2) } end end def test_arg_matching_with_string_doesnt_over_match FlexMock.use do |m| m.should_receive(:hi).with(String).returns(20) assert_failure(NO_MATCH_ERROR_MESSAGE) { m.hi(1.0) } end end def test_block_arg_given_to_no_args FlexMock.use do |m| m.should_receive(:hi).with_no_args.returns(20) assert_failure(NO_MATCH_ERROR_MESSAGE) { m.hi { 1 } } end end def test_block_arg_given_to_matching_proc FlexMock.use do |m| arg = nil m.should_receive(:hi).with(Proc).once. and_return { |block| arg = block; block.call } result = m.hi { 1 } assert_equal 1, arg.call assert_equal 1, result end end def test_arg_matching_precedence_when_best_first FlexMock.use("greeter") do |m| m.should_receive(:hi).with(1).once m.should_receive(:hi).with(FlexMock.any).never m.hi(1) end end def test_arg_matching_precedence_when_best_last_but_still_matches_first FlexMock.use("greeter") do |m| m.should_receive(:hi).with(FlexMock.any).once m.should_receive(:hi).with(1).never m.hi(1) end end def test_never_and_never_called FlexMock.use do |m| m.should_receive(:hi).with(1).never end end def test_never_and_called_once assert_failure(COUNT_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with(1).never m.hi(1) end end end def test_once_called_once FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).once m.hi(1) end end def test_once_but_never_called assert_failure(COUNT_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).once end end end def test_once_but_called_twice assert_failure(COUNT_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).once m.hi(1) m.hi(1) end end end def test_twice_and_called_twice FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).twice m.hi(1) m.hi(1) end end def test_zero_or_more_called_zero FlexMock.use do |m| m.should_receive(:hi).zero_or_more_times end end def test_zero_or_more_called_once FlexMock.use do |m| m.should_receive(:hi).zero_or_more_times m.hi end end def test_zero_or_more_called_100 FlexMock.use do |m| m.should_receive(:hi).zero_or_more_times 100.times { m.hi } end end def test_times FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).times(10) 10.times { m.hi(1) } end end def test_at_least_called_once FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_least.once m.hi(1) end end def test_at_least_but_never_called assert_failure(AT_LEAST_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_least.once end end end def test_at_least_once_but_called_twice FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_least.once m.hi(1) m.hi(1) end end def test_at_least_and_exact assert_failure(COUNT_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_least.once.once m.hi(1) m.hi(1) end end end def test_at_most_but_never_called FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_most.once end end def test_at_most_called_once FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_most.once m.hi(1) end end def test_at_most_called_twice assert_failure(AT_MOST_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_most.once m.hi(1) m.hi(1) end end end def test_at_most_and_at_least_called_never assert_failure(AT_LEAST_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_least.once.at_most.twice end end end def test_at_most_and_at_least_called_once FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_least.once.at_most.twice m.hi(1) end end def test_at_most_and_at_least_called_twice FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_least.once.at_most.twice m.hi(1) m.hi(1) end end def test_at_most_and_at_least_called_three_times assert_failure(AT_MOST_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with(1).returns(10).at_least.once.at_most.twice m.hi(1) m.hi(1) m.hi(1) end end end def test_call_counts_only_apply_to_matching_args FlexMock.use do |m| m.should_receive(:hi).with(1).once m.should_receive(:hi).with(2).twice m.should_receive(:hi).with(3) m.hi(1) m.hi(2) m.hi(2) 20.times { m.hi(3) } end end def test_call_counts_only_apply_to_matching_args_with_mismatch ex = assert_failure(COUNT_ERROR_MESSAGE) do FlexMock.use do |m| m.should_receive(:hi).with(1).once m.should_receive(:hi).with(2).twice m.should_receive(:hi).with(3) m.should_receive(:lo) m.hi(1) m.hi(2) m.lo 20.times { m.hi(3) } end end assert_match(/hi\(2\)/, ex.message) end def test_ordered_calls_in_order_will_pass FlexMock.use 'm' do |m| m.should_receive(:hi).ordered m.should_receive(:lo).ordered m.hi m.lo end end def test_ordered_calls_out_of_order_will_fail assert_failure(OUT_OF_ORDER_ERROR_MESSAGE) do FlexMock.use 'm' do |m| m.should_receive(:hi).ordered m.should_receive(:lo).ordered m.lo m.hi end end end def test_order_calls_with_different_arg_lists_and_in_order_will_pass FlexMock.use 'm' do |m| m.should_receive(:hi).with("one").ordered m.should_receive(:hi).with("two").ordered m.hi("one") m.hi("two") end end def test_order_calls_with_different_arg_lists_and_out_of_order_will_fail assert_failure(OUT_OF_ORDER_ERROR_MESSAGE) do FlexMock.use 'm' do |m| m.should_receive(:hi).with("one").ordered m.should_receive(:hi).with("two").ordered m.hi("two") m.hi("one") end end end def test_unordered_calls_do_not_effect_ordered_testing FlexMock.use 'm' do |m| m.should_receive(:blah) m.should_receive(:hi).ordered m.should_receive(:lo).ordered m.blah m.hi m.blah m.lo m.blah end end def test_ordered_with_multiple_calls_will_pass FlexMock.use 'm' do |m| m.should_receive(:hi).ordered m.should_receive(:lo).ordered m.hi m.hi m.lo m.lo end end def test_grouped_ordering_with_numbers FlexMock.use 'm' do |m| m.should_receive(:start).ordered(1) m.should_receive(:flip).ordered(2) m.should_receive(:flop).ordered(2) m.should_receive(:final).ordered m.start m.flop m.flip m.flop m.final end end def test_grouped_ordering_with_symbols FlexMock.use 'm' do |m| m.should_receive(:start).ordered(:start_group) m.should_receive(:flip).ordered(:flip_flop_group) m.should_receive(:flop).ordered(:flip_flop_group) m.should_receive(:final).ordered m.start m.flop m.flip m.flop m.final end end def test_explicit_ordering_mixed_with_implicit_ordering_should_not_overlap FlexMock.use 'm' do |m| xstart = m.should_receive(:start).ordered xmid = m.should_receive(:mid).ordered(:group_name) xend = m.should_receive(:end).ordered assert xstart.order_number < xmid.order_number assert xmid.order_number < xend.order_number end end def test_explicit_ordering_with_explicit_misorders assert_failure(OUT_OF_ORDER_ERROR_MESSAGE) do FlexMock.use 'm' do |m| m.should_receive(:hi).ordered(:first_group) m.should_receive(:lo).ordered(:second_group) m.lo m.hi end end # TODO: It would be nice to get the group names in the error message. # assert_match /first_group/, ex.message # assert_match /second_group/, ex.message end # Test submitted by Mikael Pahmp to correct expectation matching. def test_ordering_with_explicit_no_args_matches_correctly FlexMock.use("m") do |m| m.should_receive(:foo).with_no_args.once.ordered m.should_receive(:bar).with_no_args.once.ordered m.should_receive(:foo).with_no_args.once.ordered m.foo m.bar m.foo end end # Test submitted by Mikael Pahmp to correct expectation matching. def test_ordering_with_any_arg_matching_correctly_matches FlexMock.use("m") do |m| m.should_receive(:foo).with_any_args.once.ordered m.should_receive(:bar).with_any_args.once.ordered m.should_receive(:foo).with_any_args.once.ordered m.foo m.bar m.foo end end def test_ordering_between_mocks_is_not_normally_defined FlexMock.use("x", "y") do |x, y| x.should_receive(:one).ordered y.should_receive(:two).ordered assert_nothing_raised do y.two x.one end end end def test_ordering_between_mocks_is_honored_for_global_ordering assert_failure(OUT_OF_ORDER_ERROR_MESSAGE) do FlexMock.use("x", "y") do |x, y| x.should_receive(:one).globally.ordered y.should_receive(:two).globally.ordered y.two x.one end end end def test_expectation_formating mock = flexmock("m") exp = mock.should_receive(:f).with(1,"two", /^3$/). and_return(0).at_least.once mock.f(1, "two", 3) assert_equal 'f(1, "two", /^3$/)', exp.to_s end def test_multi_expectation_formatting mock = flexmock("mock") exp = mock.should_receive(:f, :g).with(1) assert_equal "[f(1), g(1)]", exp.to_s end def test_explicit_ordering_with_limits_allow_multiple_return_values FlexMock.use('mock') do |m| m.should_receive(:f).with(2).once.and_return { :first_time } m.should_receive(:f).with(2).twice.and_return { :second_or_third_time } m.should_receive(:f).with(2).and_return { :forever } assert_equal :first_time, m.f(2) assert_equal :second_or_third_time, m.f(2) assert_equal :second_or_third_time, m.f(2) assert_equal :forever, m.f(2) assert_equal :forever, m.f(2) assert_equal :forever, m.f(2) assert_equal :forever, m.f(2) assert_equal :forever, m.f(2) assert_equal :forever, m.f(2) assert_equal :forever, m.f(2) end end def test_global_methods_can_be_mocked m = flexmock("m") m.should_receive(:mock_top_level_function).and_return(:mock) assert_equal :mock, m.mock_top_level_function end def test_kernel_methods_can_be_mocked m = flexmock("m") m.should_receive(:mock_kernel_function).and_return(:mock) assert_equal :mock, m.mock_kernel_function end def test_undefing_kernel_methods_dont_effect_other_mocks m = flexmock("m") m2 = flexmock("m2") m.should_receive(:mock_kernel_function).and_return(:mock) assert_equal :mock, m.mock_kernel_function assert_equal :mkf, m2.mock_kernel_function end def test_expectations_can_by_marked_as_default m = flexmock("m") m.should_receive(:foo).and_return(:bar).by_default assert_equal :bar, m.foo end def test_default_expectations_are_search_in_the_proper_order m = flexmock("m") m.should_receive(:foo).with(Integer).once.and_return(:first).by_default m.should_receive(:foo).with(1).and_return(:second).by_default assert_equal :first, m.foo(1) assert_equal :second, m.foo(1) end def test_expectations_with_count_constraints_can_by_marked_as_default m = flexmock("m") m.should_receive(:foo).and_return(:bar).once.by_default assert_raise assertion_failed_error do flexmock_teardown end end def test_default_expectations_are_overridden_by_later_expectations m = flexmock("m") m.should_receive(:foo).and_return(:bar).once.by_default m.should_receive(:foo).and_return(:bar).twice m.foo m.foo end def test_default_expectations_can_be_changed_by_later_expectations m = flexmock("m") m.should_receive(:foo).with(1).and_return(:bar).once.by_default m.should_receive(:foo).with(2).and_return(:baz).once assert_raise assertion_failed_error do # This expectation should be hidded by the non-result m.foo(1) end m.foo(2) end def test_ordered_default_expectations_can_be_specified m = flexmock("m") m.should_receive(:foo).ordered.by_default m.should_receive(:bar).ordered.by_default m.bar assert_raise assertion_failed_error do m.foo end end def test_ordered_default_expectations_can_be_overridden m = flexmock("m") m.should_receive(:foo).ordered.by_default m.should_receive(:bar).ordered.by_default m.should_receive(:bar).ordered m.should_receive(:foo).ordered m.bar m.foo end def test_by_default_works_at_mock_level m = flexmock("m", :foo => :bar, :pooh => :bear, :who => :dey).by_default m.should_receive(:pooh => :winnie) assert_equal :bar, m.foo assert_equal :dey, m.who assert_equal :winnie, m.pooh end def test_by_default_at_mock_level_does_nothing_with_no_expectations assert_nothing_raised do flexmock("m").by_default end end def test_partial_mocks_can_have_default_expectations obj = Object.new flexmock(obj).should_receive(:foo).and_return(:bar).by_default assert_equal :bar, obj.foo end def test_partial_mocks_can_have_default_expectations_overridden obj = Object.new flexmock(obj).should_receive(:foo).and_return(:bar).by_default flexmock(obj).should_receive(:foo).and_return(:baz) assert_equal :baz, obj.foo end def test_wicked_and_evil_tricks_with_by_default_are_thwarted mock = flexmock("mock") exp = mock.should_receive(:foo).and_return(:first).once mock.should_receive(:foo).and_return(:second) ex = assert_raise(FlexMock::UsageError) do exp.by_default end assert_match %r(previously defined), ex.message assert_equal :first, mock.foo assert_equal :second, mock.foo end def test_mocks_can_handle_multi_parameter_respond_tos mock = flexmock("a mock", :foo => :bar) assert mock.respond_to?(:foo) assert mock.respond_to?(:foo, true) assert mock.respond_to?(:foo, false) assert ! mock.respond_to?(:phoo) assert ! mock.respond_to?(:phoo, false) assert ! mock.respond_to?(:phoo, true) end def test_can_mock_operators assert_operator(:[]) { |m| m[1] } assert_operator(:[]=) { |m| m[1] = :value } assert_operator(:**) { |m| m ** :x } assert_operator(:+@) { |m| +m } assert_operator(:-@) { |m| -m } assert_operator(:+) { |m| m + :x } assert_operator(:-) { |m| m - :x } assert_operator(:*) { |m| m * :x } assert_operator(:"/") { |m| m / :x } assert_operator(:%) { |m| m % :x } assert_operator(:~) { |m| ~m } # ) assert_operator(:&) { |m| m & :x } assert_operator(:|) { |m| m | :x } assert_operator(:^) { |m| m ^ :x } assert_operator(:<) { |m| m < :x } assert_operator(:>) { |m| m > :x } assert_operator(:>=) { |m| m >= :x } assert_operator(:<=) { |m| m <= :x } assert_operator(:==) { |m| m == :x } assert_operator(:===) { |m| m === :x } assert_operator(:<<) { |m| m << :x } assert_operator(:>>) { |m| m >> :x } assert_operator(:<=>) { |m| m <=> :x } assert_operator(:=~) { |m| m =~ :x } assert_operator(:"`") { |m| m.`("command") } # ` end private def assert_operator(op, &block) m = flexmock("mock") m.should_receive(op).and_return(:value) assert_equal :value, block.call(m) end end class TestFlexMockShouldsWithInclude < Test::Unit::TestCase include FlexMock::ArgumentTypes def test_include_enables_unqualified_arg_type_references FlexMock.use("x") do |m| m.should_receive(:hi).with(any).once m.hi(1) end end end class TestFlexMockArgTypesDontLeak < Test::Unit::TestCase def test_unqualified_arg_type_references_are_undefined_by_default ex = assert_raise(NameError) do FlexMock.use("x") do |m| m.should_receive(:hi).with(any).once m.hi(1) end end assert_match(/\bany\b/, ex.message, "Error message should mention 'any'") end end flexmock-0.9.0/test/should_ignore_missing_test.rb0000644000175000017500000000411711661521733022507 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' class TestShouldIgnoreMissing < Test::Unit::TestCase include FlexMock::TestCase def setup @mock = flexmock("mock") end def test_mocks_do_not_respond_to_undefined_methods assert !@mock.respond_to?(:unknown_foo) end def test_mocks_do_respond_to_defined_methods @mock.should_receive(:known_foo => :bar) assert @mock.respond_to?(:known_foo) end def test_mocks_do_respond_to_any_method_when_ignoring_missing @mock.should_ignore_missing assert @mock.respond_to?(:unknown_foo) end def test_ignored_methods_return_undefined @mock.should_ignore_missing assert_equal FlexMock.undefined, @mock.unknown_foo @mock.unknown_foo.bar.baz.bleep end def test_undefined_mocking_with_arguments @mock.should_ignore_missing assert_equal FlexMock.undefined, @mock.xyzzy(1,:two,"three") end def test_method_chains_with_undefined_are_self_preserving @mock.should_ignore_missing assert_equal FlexMock.undefined, @mock.a.b.c.d.e.f(1).g.h.i.j end def test_method_proc_raises_error_on_unknown assert_raises(NameError) { @mock.method(:unknown_foo) } end def test_method_returns_callable_proc @mock.should_receive(:known_foo).once method_proc = @mock.method(:known_foo) assert_not_nil method_proc method_proc.call end def test_not_calling_method_proc_will_fail_count_constraints @mock.should_receive(:known_foo).once method_proc = @mock.method(:known_foo) assert_not_nil method_proc assert_raises assertion_failed_error do flexmock_teardown end end def test_method_returns_do_nothing_proc_for_missing_methods @mock.should_ignore_missing method_proc = @mock.method(:plugh) assert_not_nil method_proc assert_equal FlexMock.undefined, method_proc.call end end flexmock-0.9.0/test/samples_test.rb0000644000175000017500000001515111661521733017561 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' # Sample FlexMock Usage. class TestSamples < Test::Unit::TestCase include FlexMock::TestCase # This is a basic example where we setup a mock object to mimic an # IO object. We know that the +count_lines+ method uses gets, so we # tell the mock object to handle +gets+ by returning successive # elements of an array (just as the real +gets+ returns successive # elements of a file. def test_file_io mock_file = flexmock("file") mock_file.should_receive(:gets).and_return("line 1", "line 2", nil) assert_equal 2, count_lines(mock_file) end # Count the number of lines in a file. Used in the test_file_io # test. def count_lines(file) n = 0 while file.gets n += 1 end n end end class TestUndefined < Test::Unit::TestCase include FlexMock::TestCase def test_undefined_values m = flexmock("mock") m.should_receive(:divide_by).with(0). and_return_undefined assert_equal FlexMock.undefined, m.divide_by(0) end end class TestSimple < Test::Unit::TestCase include FlexMock::TestCase def test_simple_mock m = flexmock(:pi => 3.1416, :e => 2.71) assert_equal 3.1416, m.pi assert_equal 2.71, m.e end end class TestDog < Test::Unit::TestCase include FlexMock::TestCase def test_dog_wags tail_mock = flexmock(:wag => :happy) assert_equal :happy, tail_mock.wag end end class Woofer end class Dog def initialize @woofer = Woofer.new end def bark @woofer.woof end def wag :happy end end class TestDogBarking < Test::Unit::TestCase include FlexMock::TestCase # Setup the tests by mocking the +new+ method of # Woofer and return a mock woofer. def setup @dog = Dog.new flexmock(@dog, :bark => :grrr) end def test_dog assert_equal :grrr, @dog.bark # Mocked Method assert_equal :happy, @dog.wag # Normal Method end end class TestDogBarkingWithNewInstances < Test::Unit::TestCase include FlexMock::TestCase # Setup the tests by mocking Woofer to always # return partial mocks. def setup flexmock(Woofer).new_instances.should_receive(:woof => :grrr) end def test_dog assert_equal :grrr, Dog.new.bark # All dog objects assert_equal :grrr, Dog.new.bark # are mocked. end end class TestDefaults < Test::Unit::TestCase include FlexMock::TestCase def setup @mock_dog = flexmock("Fido") @mock_dog.should_receive(:tail => :a_tail, :bark => "woof").by_default end def test_something_where_bark_must_be_called_once @mock_dog.should_receive(:bark => "bow wow").once assert_equal "bow wow", @mock_dog.bark assert_equal :a_tail, @mock_dog.tail end end class TestDemeter < Test::Unit::TestCase include FlexMock::TestCase def test_manual_mocking # Manually mocking a Law of Demeter violation cog = flexmock("cog") cog.should_receive(:turn).once.and_return(:ok) joint = flexmock("gear", :cog => cog) axle = flexmock("axle", :universal_joint => joint) chassis = flexmock("chassis", :axle => axle) car = flexmock("car", :chassis => chassis) # test code assert_equal :ok, car.chassis.axle.universal_joint.cog.turn end def test_demeter car = flexmock("car") car.should_receive( "chassis.axle.universal_joint.cog.turn" => :ok).once # Test code assert_equal :ok, car.chassis.axle.universal_joint.cog.turn end end class TestDb < Test::Unit::TestCase include FlexMock::TestCase def test_db db = flexmock('db') db.should_receive(:query).and_return([1,2,3]) db.should_receive(:update).with(5).and_return(nil).once # test code assert_nil db.update(5) end end class TestDb < Test::Unit::TestCase include FlexMock::TestCase def test_query_and_update db = flexmock('db') db.should_receive(:query).and_return([1,2,3]).ordered db.should_receive(:update).and_return(nil).ordered # test code here assert_raises(assertion_failed_error) do db.update db.query end end def test_ordered_queries db = flexmock('db') db.should_receive(:startup).once.ordered db.should_receive(:query).with("CPWR").and_return(12.3). once.ordered(:queries) db.should_receive(:query).with("MSFT").and_return(10.0). once.ordered(:queries) db.should_receive(:query).with(/^....$/).and_return(3.3). at_least.once.ordered(:queries) db.should_receive(:finish).once.ordered # test code here db.startup db.query("CPWR") db.query("MSFT") db.query("asdf") db.finish end def test_ordered_queries_in_record_mode db = flexmock('db') db.should_expect do |rec| rec.startup.once.ordered rec.query("CPWR") { 12.3 }.once.ordered(:queries) rec.query("MSFT") { 10.0 }.once.ordered(:queries) rec.query(/^....$/) { 3.3 }.at_least.once.ordered(:queries) rec.finish.once.ordered end # test code here using +db+. db.startup db.query("CPWR") db.query("MSFT") db.query("asdf") db.finish end def known_good_way_to_build_xml(builder) builder.html end def new_way_to_build_xml(builder) known_good_way_to_build_xml(builder) end def test_build_xml builder = flexmock('builder') builder.should_expect do |rec| rec.should_be_strict known_good_way_to_build_xml(rec) # record the messages end new_way_to_build_xml(builder) # compare to new way end end class TestMoreSamples < Test::Unit::TestCase include FlexMock::TestCase def test_multiple_gets file = flexmock('file') file.should_receive(:gets).with_no_args. and_return("line 1\n", "line 2\n") # test code here assert_equal "line 1\n", file.gets assert_equal "line 2\n", file.gets end def test_an_important_message m = flexmock('m') m.should_receive(:an_important_message).and_return(1).once m.should_ignore_missing # test code here assert_equal 1, m.an_important_message assert_equal FlexMock.undefined, m.other end class QuoteService end class Portfolio def initialize @quote_service = QuoteService.new end def value @quote_service.quote end end def test_portfolio_value flexmock(QuoteService).new_instances do |m| m.should_receive(:quote).and_return(100) end port = Portfolio.new value = port.value # Portfolio calls QuoteService.quote assert_equal 100, value end end flexmock-0.9.0/test/rspec_integration/0000755000175000017500000000000011661521733020245 5ustar terceiroterceiroflexmock-0.9.0/test/rspec_integration/integration_spec.rb0000755000175000017500000000214011661521733024127 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ if defined?(RSpec) RSpec.configure do |config| config.mock_with :flexmock end else Spec::Runner.configure do |config| config.mock_with :flexmock end end describe "FlexMock in a RSpec example" do specify "should be able to create a mock" do m = flexmock() end specify "should have an error when a mock is not called" do m = flexmock("Expectation Failured") m.should_receive(:hi).with().once end specify "should be able to create a stub" do s = "Hello World" flexmock(:base, s).should_receive(:downcase).with().once.and_return("hello WORLD") s.downcase.should == "hello WORLD" end specify "Should show an example failure" do 1.should == 2 end specify "Should show how mocks are displayed in error messages" do m = flexmock("x") m.should == 2 end end flexmock-0.9.0/test/redirect_error.rb0000644000175000017500000000042111661521733020062 0ustar terceiroterceirorequire 'stringio' class FlexMock module RedirectError def redirect_error require 'stringio' old_err = $stderr $stderr = StringIO.new yield $stderr.string ensure $stderr = old_err end private :redirect_error end end flexmock-0.9.0/test/record_mode_test.rb0000644000175000017500000000670411661521733020403 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' class TestRecordMode < Test::Unit::TestCase include FlexMock::TestCase def test_recording_mode_works mock = flexmock("mock") mock.should_expect do |recorder| recorder.f { :answer } end assert_equal :answer, mock.f end def test_arguments_are_passed_to_recording_mode_block mock = flexmock("mock") mock.should_expect do |recorder| recorder.f(:arg) do |arg| assert_equal :arg, arg :answer end end assert_equal :answer, mock.f(:arg) end def test_recording_mode_handles_multiple_returns FlexMock.use("mock") do |mock| mock.should_expect do |r| answers = [1, 2] # HACK: The following lambda is needed in Ruby 1.9 to cause # the answers to be properly bound in the following block. lambda { } r.f { answers.shift } end assert_equal 1, mock.f assert_equal 2, mock.f end end def test_recording_mode_does_not_specify_order FlexMock.use("mock") do |mock| mock.should_expect do |r| r.f { 1 } r.g { 2 } end assert_equal 2, mock.g assert_equal 1, mock.f end end def test_recording_mode_gets_block_args_too mock = flexmock("mock") mock.should_expect do |r| r.f(1, Proc) { |arg, block| assert_not_nil block block.call } end assert_equal :block_result, mock.f(1) { :block_result } end def test_recording_mode_should_validate_args_with_equals assert_failure do FlexMock.use("mock") do |mock| mock.should_expect do |r| r.f(1) end mock.f(2) end end end def test_recording_mode_should_allow_arg_contraint_validation assert_failure do FlexMock.use("mock") do |mock| mock.should_expect do |r| r.f(1) end mock.f(2) end end end def test_recording_mode_should_handle_multiplicity_contraints assert_failure do FlexMock.use("mock") do |mock| mock.should_expect do |r| r.f { :result }.once end mock.f mock.f end end end def test_strict_record_mode_requires_exact_argument_matches assert_failure do FlexMock.use("mock") do |mock| mock.should_expect do |rec| rec.should_be_strict rec.f(Integer) end mock.f(3) end end end def test_strict_record_mode_requires_exact_ordering assert_failure do FlexMock.use("mock") do |mock| mock.should_expect do |rec| rec.should_be_strict rec.f(1) rec.f(2) end mock.f(2) mock.f(1) end end end def test_strict_record_mode_requires_once assert_failure do FlexMock.use("mock") do |mock| mock.should_expect do |rec| rec.should_be_strict rec.f(1) end mock.f(1) mock.f(1) end end end def test_strict_record_mode_can_not_fail FlexMock.use("mock") do |mock| mock.should_expect do |rec| rec.should_be_strict rec.f(Integer) rec.f(2) end mock.f(Integer) mock.f(2) end end end flexmock-0.9.0/test/rails_view_stub_test.rb0000644000175000017500000000637111661521733021322 0ustar terceiroterceiro#!/usr/bin/env ruby require 'test/test_setup' require 'flexmock/rails/view_mocking' module ViewTests def test_view_mocks_as_stub should_render_view render "controller/new.rthml" end def test_fails_if_no_render should_render_view assert_raise(assertion_failed_error) do flexmock_verify end end def test_view_mocks_with_expectation should_render_view("new") render "controller/new" end def test_view_mocks_with_expectation_fails_with_different_template should_render_view("new") render "controller/edit" assert_raise(assertion_failed_error) do flexmock_verify end end def test_view_mocks_with_expectation_and_multiple_templates should_render_view("new") render "controller/edit", "controller/show", "controller/new" end private def pretend_to_be_rails_version(version) flexmock(self).should_receive(:rails_version).and_return(version) end end ###################################################################### class TestRailsViewStubForVersionsUpTo_1_2_4 < Test::Unit::TestCase include FlexMock::TestCase include ViewTests def setup @controller_class = flexmock("controller class") @controller = flexmock("controller", :class => @controller_class) pretend_to_be_rails_version("1.2.4") end # Simulate Rails rendering in version 1.2.4 def render(*names) vc = @controller.class.view_class v = vc.new v.assigns(:x => :y) v.render_file v.first_render names.each do |name| v.file_exists?(name) end end end ###################################################################### class TestRailsViewStubForVersionsAfter_1_2_4 < Test::Unit::TestCase include FlexMock::TestCase include ViewTests def setup @controller_class = flexmock("controller class") @controller = flexmock("controller", :class => @controller_class) @response = flexmock("Response") pretend_to_be_rails_version("2.0") end # Simulate Rails rendering after Rails version 1.2.4 def render(*names) v = @response.template v.assigns(:x => :y) v.render_file v.template_format v.view_paths v.pick_template_extension names.each do |name| v.file_exists?(name) end end end ###################################################################### class TestRailsViewStubForVersionsAfter_2_0_2 < Test::Unit::TestCase include FlexMock::TestCase include ViewTests def setup @controller_class = flexmock("controller class") @controller = flexmock("controller", :class => @controller_class) @response = flexmock("Response") pretend_to_be_rails_version("2.0.2") end # Simulate Rails rendering after Rails version 2.0.2 def render(*names) v = ActionView::Base.new v.assigns(:x => :y) v.template_format v.view_paths v.pick_template_extension names.each do |name| v.file_exists?(name) end v.render_file(names.last, nil, nil) end end class FlexMock module MockContainer module Rails module VERSION STRING = 1 end end end end class TestRailsVersion < Test::Unit::TestCase include FlexMock::TestCase def test_rails_version_to_get_code_coverage rails_version end end # Test Helper Classes module ActionView class Base end end flexmock-0.9.0/test/partial_mock_test.rb0000644000175000017500000002337611661521733020572 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' class TestStubbing < Test::Unit::TestCase include FlexMock::TestCase class Dog def bark :woof end def Dog.create :new_dog end end class DogPlus < Dog def should_receive :dog_should end def new_instances :dog_new end def by_default :dog_by_default end end def test_stub_command_add_behavior_to_arbitrary_objects obj = Object.new flexmock(obj).should_receive(:hi).once.and_return(:stub_hi) assert_equal :stub_hi, obj.hi end def test_stub_command_can_configure_via_block obj = Object.new flexmock(obj) do |m| m.should_receive(:hi).once.and_return(:stub_hi) end assert_equal :stub_hi, obj.hi end def test_stubbed_methods_can_take_blocks obj = Object.new flexmock(obj).should_receive(:with_block).once.with(Proc). and_return { |block| block.call } assert_equal :block, obj.with_block { :block } end def test_multiple_stubs_on_the_same_object_reuse_the_same_partial_mock obj = Object.new assert_equal flexmock(obj), flexmock(obj) end def test_multiple_methods_can_be_stubbed dog = Dog.new flexmock(dog).should_receive(:bark).and_return(:grrrr) flexmock(dog).should_receive(:wag).and_return(:happy) assert_equal :grrrr, dog.bark assert_equal :happy, dog.wag end def test_original_behavior_can_be_restored dog = Dog.new partial_mock = flexmock(dog) partial_mock.should_receive(:bark).once.and_return(:growl) assert_equal :growl, dog.bark partial_mock.flexmock_teardown assert_equal :woof, dog.bark assert_equal nil, dog.instance_variable_get("@flexmock_proxy") end def test_original_missing_behavior_can_be_restored obj = Object.new partial_mock = flexmock(obj) partial_mock.should_receive(:hi).once.and_return(:ok) assert_equal :ok, obj.hi partial_mock.flexmock_teardown assert_raise(NoMethodError) { obj.hi } end def test_multiple_stubs_on_single_method_can_be_restored_missing_method obj = Object.new partial_mock = flexmock(obj) partial_mock.should_receive(:hi).with(1).once.and_return(:ok) partial_mock.should_receive(:hi).with(2).once.and_return(:ok) assert_equal :ok, obj.hi(1) assert_equal :ok, obj.hi(2) partial_mock.flexmock_teardown assert_raise(NoMethodError) { obj.hi } end def test_original_behavior_is_restored_when_multiple_methods_are_mocked dog = Dog.new flexmock(dog).should_receive(:bark).and_return(:grrrr) flexmock(dog).should_receive(:wag).and_return(:happy) flexmock(dog).flexmock_teardown assert_equal :woof, dog.bark assert_raise(NoMethodError) { dog.wag } end def test_original_behavior_is_restored_on_class_objects flexmock(Dog).should_receive(:create).once.and_return(:new_stub) assert_equal :new_stub, Dog.create flexmock(Dog).flexmock_teardown assert_equal :new_dog, Dog.create end def test_original_behavior_is_restored_on_singleton_methods obj = Object.new def obj.hi() :hello end flexmock(obj).should_receive(:hi).once.and_return(:hola) assert_equal :hola, obj.hi flexmock(obj).flexmock_teardown assert_equal :hello, obj.hi end def test_original_behavior_is_restored_on_singleton_methods_with_multiple_stubs obj = Object.new def obj.hi(n) "hello#{n}" end flexmock(obj).should_receive(:hi).with(1).once.and_return(:hola) flexmock(obj).should_receive(:hi).with(2).once.and_return(:hola) assert_equal :hola, obj.hi(1) assert_equal :hola, obj.hi(2) flexmock(obj).flexmock_teardown assert_equal "hello3", obj.hi(3) end def test_original_behavior_is_restored_on_nonsingleton_methods_with_multiple_stubs flexmock(Dir).should_receive(:chdir).with("xx").once.and_return(:ok1) flexmock(Dir).should_receive(:chdir).with("yy").once.and_return(:ok2) assert_equal :ok1, Dir.chdir("xx") assert_equal :ok2, Dir.chdir("yy") flexmock(Dir).flexmock_teardown x = :not_called Dir.chdir("test") do assert_match %r{/test$}, Dir.pwd x = :called end assert_equal :called, x end def test_stubbing_file_shouldnt_break_writing flexmock(File).should_receive(:open).with("foo").once.and_return(:ok) assert_equal :ok, File.open("foo") flexmock(File).flexmock_teardown File.open("dummy.txt", "w") do |out| assert out.is_a?(IO) out.puts "XYZ" end text = nil File.open("dummy.txt") { |f| text = f.read } assert_equal "XYZ\n", text ensure FileUtils.rm_f("dummy.txt") end def test_original_behavior_is_restored_even_when_errors flexmock(Dog).should_receive(:create).once.and_return(:mock) begin flexmock_teardown rescue assertion_failed_error => _ nil end assert_equal :new_dog, Dog.create # Now disable the mock so that it doesn't cause errors on normal # test teardown m = flexmock(Dog).flexmock_get def m.flexmock_verify() end end def test_not_calling_stubbed_method_is_an_error dog = Dog.new flexmock(dog).should_receive(:bark).once assert_raise(assertion_failed_error) { flexmock(dog).flexmock_verify } dog.bark end def test_mock_is_verified_when_the_stub_is_verified obj = Object.new partial_mock = flexmock(obj) partial_mock.should_receive(:hi).once.and_return(:ok) assert_raise(assertion_failed_error) { partial_mock.flexmock_verify } end def test_stub_can_have_explicit_name obj = Object.new partial_mock = flexmock(obj, "Charlie") assert_equal "Charlie", partial_mock.flexmock_get.flexmock_name end def test_unamed_stub_will_use_default_naming_convention obj = Object.new partial_mock = flexmock(obj) assert_equal "flexmock(Object)", partial_mock.flexmock_get.flexmock_name end def test_partials_can_be_defined_in_a_block dog = Dog.new flexmock(dog) do |m| m.should_receive(:bark).and_return(:growl) end assert_equal :growl, dog.bark end def test_partials_defining_block_return_real_obj_not_proxy dog = flexmock(Dog.new) do |m| m.should_receive(:bark).and_return(:growl) end assert_equal :growl, dog.bark end def test_partial_mocks_always_return_domain_object dog = Dog.new assert_equal dog, flexmock(dog) assert_equal dog, flexmock(dog) { } end MOCK_METHOD_SUBSET = [ :should_receive, :new_instances, :flexmock_get, :flexmock_teardown, :flexmock_verify, ] def test_domain_objects_do_not_have_mock_methods dog = Dog.new MOCK_METHOD_SUBSET.each do |sym| assert ! dog.respond_to?(sym), "should not have :#{sym} defined" end end def test_partial_mocks_have_mock_methods dog = Dog.new flexmock(dog) MOCK_METHOD_SUBSET.each do |sym| assert dog.respond_to?(sym), "should have :#{sym} defined" end end def test_partial_mocks_do_not_have_mock_methods_after_teardown dog = Dog.new flexmock(dog) dog.flexmock_teardown MOCK_METHOD_SUBSET.each do |sym| assert ! dog.respond_to?(sym), "should not have :#{sym} defined" end end def test_partial_mocks_with_mock_method_singleton_colision_have_original_defs_restored dog = Dog.new def dog.mock() :original end flexmock(dog) dog.flexmock_teardown assert_equal :original, dog.mock end class MockColision def mock :original end end def test_partial_mocks_with_mock_method_non_singleton_colision_have_original_defs_restored mc = MockColision.new flexmock(mc) mc.flexmock_teardown assert_equal :original, mc.mock end def test_safe_partial_mocks_do_not_support_mock_methods dog = Dog.new flexmock(:safe, dog) { } MOCK_METHOD_SUBSET.each do |sym| assert ! dog.respond_to?(sym), "should not have :#{sym} defined" end end def test_safe_partial_mocks_require_block dog = Dog.new assert_raise(FlexMock::UsageError) { flexmock(:safe, dog) } end def test_safe_partial_mocks_are_actually_mocked dog = flexmock(:safe, Dog.new) { |m| m.should_receive(:bark => :mocked) } assert_equal :mocked, dog.bark end def test_should_receive_does_not_override_preexisting_def dog = flexmock(DogPlus.new) assert_equal :dog_new, dog.new_instances assert_equal :dog_by_default, dog.by_default end def test_should_receive_does_override_should_receive_preexisting_def dog = flexmock(DogPlus.new) assert_kind_of FlexMock::CompositeExpectation, dog.should_receive(:x) end class Liar def respond_to?(method_name) sym = method_name.to_sym if sym == :not_defined true else super(method_name) end end end def test_liar_actually_lies liar = Liar.new assert liar.respond_to?(:not_defined) assert_raise(NoMethodError) { liar.not_defined } end def test_partial_mock_where_respond_to_is_true_yet_method_is_not_there liar = Liar.new flexmock(liar, :not_defined => :xyzzy) assert_equal :xyzzy, liar.not_defined end # The following test was suggested by Pat Maddox for the RSpec # mocks. Evidently the (poorly implemented) == method caused issues # with RSpec Mock's internals. I'm just double checking for any # similar issues in FlexMock as well. class ValueObject attr_reader :val def initialize(val) @val = val end def ==(other) @val == other.val end end def test_partial_mocks_in_the_presense_of_equal_definition flexmock("existing obj", :foo => :foo) obj = ValueObject.new(:bar) flexmock(obj, :some_method => :some_method) end end flexmock-0.9.0/test/new_instances_test.rb0000755000175000017500000001313511661521733020760 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' class TestNewInstances < Test::Unit::TestCase include FlexMock::TestCase include FlexMock::RedirectError class Dog def bark :woof end def wag :tail end def self.make new end end class Cat attr_reader :name def initialize(name, &block) @name = name block.call(self) if block_given? end end class Connection def initialize(*args) yield(self) if block_given? end def send(args) post(args) end def post(args) :unstubbed end end def test_new_instances_allows_stubbing_of_existing_methods flexstub(Dog).new_instances do |obj| obj.should_receive(:bark).and_return(:whimper) end m = Dog.new assert_equal :whimper, m.bark end def test_new_instances_stubs_still_have_existing_methods flexstub(Dog).new_instances do |obj| obj.should_receive(:bark).and_return(:whimper) end m = Dog.new assert_equal :tail, m.wag end def test_new_instances_will_pass_args_to_new flexstub(Cat).new_instances do |obj| obj.should_receive(:meow).and_return(:scratch) end x = :not_called m = Cat.new("Fido") { x = :called } assert_equal :scratch, m.meow assert_equal "Fido", m.name assert_equal :called, x end # Some versions of the software had problems invoking the block after a # second stubbing. def test_new_gets_block_after_restubbing flexstub(Cat).new_instances { } x = :not_called m = Cat.new("Fido") { x = :called } assert_equal :called, x flexmock_teardown flexstub(Cat).new_instances { } x = :not_called m = Cat.new("Fido") { x = :called } assert_equal :called, x end def test_new_instances_stub_verification_happens_on_teardown flexstub(Dog).new_instances do |obj| obj.should_receive(:bark).once.and_return(nil) end Dog.new ex = assert_raise(assertion_failed_error) { flexmock_teardown } assert_match(/method 'bark\(.*\)' called incorrect number of times/, ex.message) end def test_new_instances_reports_error_on_non_classes ex = assert_raise(ArgumentError) { flexstub(Dog.new).new_instances do |obj| obj.should_receive(:hi) end } assert_match(/Class/, ex.message) assert_match(/new_instances/, ex.message) end def test_does_not_by_default_stub_objects_created_with_allocate flexstub(Dog).new_instances do |obj| obj.should_receive(:bark).and_return(:whimper) end m = Dog.allocate assert_equal :woof, m.bark end if RUBY_VERSION >= "1.9" def test_explicitly_mocking_allocation_in_new_instances_fails_in_ruby_19 assert_raise FlexMock::UsageError do flexstub(Dog).new_instances(:allocate) do |obj| obj.should_receive(:bark).and_return(:whimper) end end end else def test_can_explicitly_stub_objects_created_with_allocate flexstub(Dog).new_instances(:allocate) do |obj| obj.should_receive(:bark).and_return(:whimper) end m = Dog.allocate assert_equal :whimper, m.bark end end def test_can_stub_objects_created_with_arbitrary_class_methods flexstub(Dog).new_instances(:make) do |obj| obj.should_receive(:bark).and_return(:whimper) end assert_equal :whimper, Dog.make.bark end def test_stubbing_arbitrary_class_methods_leaves_new_alone flexstub(Dog).new_instances(:make) do |obj| obj.should_receive(:bark).and_return(:whimper) end assert_equal :woof, Dog.new.bark end def test_stubbing_new_and_allocate_doesnt_double_stub_objects_on_new counter = 0 flexstub(Dog).new_instances do |obj| counter += 1 end Dog.new assert_equal 1, counter end # Current behavior does not install stubs into the block passed to new. # This is rather difficult to achieve, although it would be nice. For the # moment, we assure that they are not stubbed, but I am willing to change # this in the future. def test_blocks_on_new_do_not_have_stubs_installed flexstub(Connection).new_instances do |new_con| new_con.should_receive(:post).and_return { :stubbed } end block_run = false Connection.new do |c| assert_equal :unstubbed, c.send("hi") block_run = true end assert block_run end def test_new_instances_accept_chained_expectations flexmock(Dog).new_instances. should_receive(:growl).and_return(:grr). should_receive(:roll_over).and_return(:flip) assert_equal :grr, Dog.new.growl assert_equal :flip, Dog.new.roll_over end def test_fancy_use_of_chained_should_received flexmock(Dog).new_instances.should_receive(:woof => :grrr) assert_equal :grrr, Dog.new.woof end def test_writable_accessors flexmock(Dog).new_instances.should_receive(:name=).with("fido") dog = Dog.new dog.name = 'fido' end def test_ordering_can_be_specified dog = Dog.new flexmock(dog).should_receive(:bark).once.ordered flexmock(dog).should_receive(:bite).once.ordered dog.bark dog.bite end def test_ordering_can_be_specified_in_groups dog = Dog.new flexmock(dog).should_receive(:wag).once.ordered(:safe) flexmock(dog).should_receive(:bark).once.ordered(:danger) flexmock(dog).should_receive(:bite).once.ordered(:danger) dog.wag dog.bite dog.bark end end flexmock-0.9.0/test/naming_test.rb0000644000175000017500000000375611661521733017376 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' class TestNaming < Test::Unit::TestCase include FlexMock::TestCase def test_name m = flexmock("m") assert_equal "m", m.flexmock_name end def test_name_in_no_handler_found_error m = flexmock("mmm") ex = assert_raises(assertion_failed_error) { m.should_receive(:xx).with(1) m.xx(2) } assert_match(/'mmm'/, ex.message) end def test_name_in_received_count_error m = flexmock("mmm") ex = assert_raises(assertion_failed_error) { m.should_receive(:xx).once m.flexmock_verify } assert_match(/'mmm'/, ex.message) end def test_naming_with_use FlexMock.use("blah") do |m| assert_equal "blah", m.flexmock_name end end def test_naming_with_multiple_mocks_in_use FlexMock.use("blah", "yuk") do |a, b| assert_equal "blah", a.flexmock_name assert_equal "yuk", b.flexmock_name end end def test_inspect_returns_reasonable_name FlexMock.use("XYZZY") do |m| assert_equal "XYZZY", m.flexmock_name assert_equal "", m.inspect end end def test_mock_can_override_inspect FlexMock.use("XYZZY") do |m| m.should_receive(:inspect).with_no_args.and_return("MOCK-INSPECT") assert_equal "MOCK-INSPECT", m.inspect end end class Dummy def inspect "DUMMY-INSPECT" end end def test_partial_mocks_use_original_inspect dummy = Dummy.new flexmock(dummy).should_receive(:msg) assert_equal "DUMMY-INSPECT", dummy.inspect end def test_partial_mocks_can_override_inspect dummy = Dummy.new flexmock(dummy).should_receive(:inspect).and_return("MOCK-INSPECT") assert_equal "MOCK-INSPECT", dummy.inspect end end flexmock-0.9.0/test/flexmodel_test.rb0000644000175000017500000000253711661521733020100 0ustar terceiroterceiro#!/usr/bin/env ruby require 'test/test_setup' class DummyModel end class ChildModel < DummyModel end ###################################################################### class TestFlexModel < Test::Unit::TestCase include FlexMock::TestCase def test_initial_conditions model = flexmock(:model, DummyModel) assert_match(/^DummyModel_\d+/, model.flexmock_name) assert_equal model.id.to_s, model.to_params assert ! model.new_record? assert model.is_a?(DummyModel) # TODO: Make these work!!! assert_equal DummyModel, model.class assert model.instance_of?(DummyModel) assert model.kind_of?(DummyModel) end def test_classifying_mock_models model = flexmock(:model, ChildModel) assert model.kind_of?(ChildModel) assert model.instance_of?(ChildModel) assert model.kind_of?(DummyModel) assert ! model.instance_of?(DummyModel) end def test_mock_models_have_different_ids m1 = flexmock(:model, DummyModel) m2 = flexmock(:model, DummyModel) assert m2.id != m1.id end def test_mock_models_can_have_quick_defs model = flexmock(:model, DummyModel, :xyzzy => :ok) assert_equal :ok, model.xyzzy end def test_mock_models_can_have_blocks model = flexmock(:model, DummyModel) do |m| m.should_receive(:xyzzy => :okdokay) end assert_equal :okdokay, model.xyzzy end end flexmock-0.9.0/test/extended_should_receive_test.rb0000755000175000017500000000336011661521733022777 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require "test/test_setup" module ExtendedShouldReceiveTests def test_accepts_expectation_hash @mock.should_receive( :foo => :bar, :baz => :froz ) assert_equal :bar, @obj.foo assert_equal :froz, @obj.baz end def test_accepts_list_of_methods @mock.should_receive(:foo, :bar, "baz") assert_nil @obj.foo assert_nil @obj.bar assert_nil @obj.baz end def test_contraints_apply_to_all_expectations @mock.should_receive(:foo, :bar => :baz).with(1) ex = assert_raise(assertion_failed_error) { @obj.foo(2) } ex = assert_raise(assertion_failed_error) { @obj.bar(2) } assert_equal :baz, @obj.bar(1) end def test_count_contraints_apply_to_all_expectations @mock.should_receive(:foo, :bar => :baz).once @obj.foo assert_raise(assertion_failed_error) { @mock.flexmock_verify } end def test_multiple_should_receives_are_allowed @mock.should_receive(:hi).and_return(:bye). should_receive(:hello => :goodbye) assert_equal :bye, @obj.hi assert_equal :goodbye, @obj.hello end end class TestExtendedShouldReceiveOnFullMocks < Test::Unit::TestCase include FlexMock::TestCase include ExtendedShouldReceiveTests def setup @mock = flexmock("mock") @obj = @mock end end class TestExtendedShouldReceiveOnPartialMockProxies < Test::Unit::TestCase include FlexMock::TestCase include ExtendedShouldReceiveTests def setup @obj = Object.new @mock = flexmock(@obj, "mock") end end flexmock-0.9.0/test/examples_from_readme_test.rb0000644000175000017500000001001211661521733022262 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' class TemperatureSampler def initialize(sensor) @sensor = sensor end def average_temp total = (0...3).collect { @sensor.read_temperature }.inject { |i, s| i + s } total / 3.0 end end class TestTemperatureSampler < Test::Unit::TestCase include FlexMock::TestCase def test_tempurature_sampler readings = [10, 12, 14] mock_sensor = flexmock("sensor") mock_sensor.should_receive(:read_temperature).and_return { readings.shift } sampler = TemperatureSampler.new(mock_sensor) assert_equal 12, sampler.average_temp end end class TestExamplesFromReadme < Test::Unit::TestCase include FlexMock::TestCase def test_simple_return_values m = flexmock(:pi => 3.1416, :e => 2.71) assert_equal 3.1416, m.pi assert_equal 2.71, m.e end def test_returning_an_undefined_value m = flexmock("mock") m.should_receive(:foo).and_return_undefined m.foo.bar.baz end def test_db db = flexmock('db') db.should_receive(:query).and_return([1,2,3]) db.should_receive(:update).with(5).and_return(nil).once # test code here assert_equal [1, 2, 3], db.query db.update(5) end def test_query_and_update db = flexmock('db') db.should_receive(:query).and_return([1,2,3]).ordered db.should_receive(:update).and_return(nil).ordered # test code here assert_equal [1,2,3], db.query assert_nil db.update end def test_ordered_queries db = flexmock('db') db.should_receive(:startup).once.ordered db.should_receive(:query).with("GOOG").and_return(12.3). once.ordered(:queries) db.should_receive(:query).with("APPL").and_return(10.0). once.ordered(:queries) db.should_receive(:query).with(/^....$/).and_return(3.3). at_least.once.ordered(:queries) db.should_receive(:finish).once.ordered # test code here db.startup assert_equal 3.3, db.query("WXYZ") assert_equal 10.0, db.query("APPL") assert_equal 12.3, db.query("GOOG") db.finish end def test_ordered_queries_in_record_mode db = flexmock('db') db.should_expect do |rec| rec.startup.once.ordered rec.query("GOOG") { 12.3 }.once.ordered(:queries) rec.query("APPL") { 10.0 }.once.ordered(:queries) rec.query(/^....$/) { 3.3 }.at_least.once.ordered(:queries) rec.finish.once.ordered end # test code here using +db+. db.startup assert_equal 10.0, db.query("APPL") assert_equal 12.3, db.query("GOOG") assert_equal 3.3, db.query("WXYZ") db.finish end def test_build_xml builder = flexmock('builder') builder.should_expect do |rec| rec.should_be_strict known_good_way_to_build_xml(rec) # record the messages end new_way_to_build_xml(builder) # compare to new way end def known_good_way_to_build_xml(rec) rec.one rec.two end def new_way_to_build_xml(rec) [:one, :two].each do |sym| rec.send(sym) end end def test_multiple_gets file = flexmock('file') file.should_receive(:gets).with_no_args. and_return("line 1\n", "line 2\n") # test code here assert_equal "line 1\n", file.gets assert_equal "line 2\n", file.gets end def test_an_important_message m = flexmock('m') m.should_receive(:an_important_message).and_return(1).once m.should_ignore_missing # test code here m.an_important_message m.unknown_message.bar.baz end class QuoteService end class Portfolio def value QuoteService.new.quote end end def test_portfolio_value flexmock(QuoteService).new_instances do |m| m.should_receive(:quote).and_return(100) end port = Portfolio.new value = port.value # Portfolio calls QuoteService.quote assert_equal 100, value end end flexmock-0.9.0/test/deprecated_methods_test.rb0000644000175000017500000001232211661521733021735 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/test_setup' require 'flexmock/deprecated_methods' class TestFlexMock < Test::Unit::TestCase include FlexMock::TestCase include FlexMock::RedirectError def s(&block) redirect_error(&block) end def setup @mock = flexmock('mock') end def test_handle args = nil s { @mock.mock_handle(:hi) { |a, b| args = [a,b] } } @mock.hi(1,2) assert_equal [1,2], args end def test_handle_no_block s { @mock.mock_handle(:blip) } @mock.blip assert true, "just checking for failures" end def test_called_with_block called = false s { @mock.mock_handle(:blip) { |block| block.call } } @mock.blip { called = true } assert called, "Block to blip should be called" end def test_return_value s { @mock.mock_handle(:blip) { 10 } } assert_equal 10, @mock.blip end def test_handle_missing_method expected_error = (RUBY_VERSION >= "1.8.0") ? NoMethodError : NameError ex = assert_raises(expected_error) { @mock.not_defined } assert_match(/not_defined/, ex.message) end def test_ignore_missing_method @mock.mock_ignore_missing @mock.blip assert true, "just checking for failures" end def test_good_counts s { @mock.mock_handle(:blip, 3) } @mock.blip @mock.blip @mock.blip @mock.flexmock_verify end def test_bad_counts s { @mock.mock_handle(:blip, 3) } @mock.blip @mock.blip begin @mock.flexmock_verify rescue assertion_failed_error => err end assert_not_nil err end def test_undetermined_counts FlexMock.use('fs') { |m| s { m.mock_handle(:blip) } m.blip m.blip m.blip } end def test_zero_counts assert_raises(assertion_failed_error) do FlexMock.use { |m| s { m.mock_handle(:blip, 0) } m.blip } end end def test_file_io_with_use FlexMock.use do |m| filedata = ["line 1", "line 2"] s { m.mock_handle(:gets, 3) { filedata.shift } } assert_equal 2, count_lines(m) end end def count_lines(stream) result = 0 while stream.gets result += 1 end result end def test_use assert_raises(assertion_failed_error) { FlexMock.use do |m| s { m.mock_handle(:blip, 2) } m.blip end } end def test_failures_during_use ex = assert_raises(NameError) { FlexMock.use do |m| s { m.mock_handle(:blip, 2) } xyz end } assert_match(/undefined local variable or method/, ex.message) end def test_sequential_values values = [1,4,9,16] s { @mock.mock_handle(:get) { values.shift } } assert_equal 1, @mock.get assert_equal 4, @mock.get assert_equal 9, @mock.get assert_equal 16, @mock.get end def test_respond_to_returns_false_for_non_handled_methods assert(!@mock.respond_to?(:blah), "should not respond to blah") end def test_respond_to_returns_true_for_explicit_methods s { @mock.mock_handle(:xyz) } assert(@mock.respond_to?(:xyz), "should respond to test") end def test_respond_to_returns_true_for_missing_methods_when_ignoring_missing @mock.mock_ignore_missing assert(@mock.respond_to?(:yada), "should respond to yada now") end def test_respond_to_returns_true_for_missing_methods_when_ignoring_missing_using_should @mock.should_ignore_missing assert(@mock.respond_to?(:yada), "should respond to yada now") end def test_method_proc_raises_error_on_unknown assert_raises(NameError) { @mock.method(:xyzzy) } end def test_method_returns_callable_proc got_it = false s { @mock.mock_handle(:xyzzy) { got_it = true } } method_proc = @mock.method(:xyzzy) assert_not_nil method_proc method_proc.call assert(got_it, "method proc should run") end def test_method_returns_do_nothing_proc_for_missing_methods @mock.mock_ignore_missing method_proc = @mock.method(:plugh) assert_not_nil method_proc assert_equal FlexMock.undefined, method_proc.call end end class TestDeprecatedOrderingMethods < Test::Unit::TestCase include FlexMock::TestCase include FlexMock::RedirectError def test_deprecated_ordering_methods flexmock(:x).should_receive(:msg).globally.ordered(:testgroup) assert_equal({ :testgroup => 1 }, flexmock_groups) message = redirect_error do assert_equal({ :testgroup => 1 }, mock_groups) end assert_match(/deprecated/i, message) assert_match(/\bmock_groups/, message) assert_match(/\bflexmock_groups/, message) end end class TestAnyInstance < Test::Unit::TestCase include FlexMock::TestCase include FlexMock::RedirectError class Dog def bark :woof end end def test_any_instance_still_works_for_backwards_compatibility message = redirect_error do flexstub(Dog).any_instance do |obj| obj.should_receive(:bark).and_return(:whimper) assert_match(/deprecated/, message) end end m = Dog.new assert_equal :whimper, m.bark end end flexmock-0.9.0/test/demeter_mocking_test.rb0000644000175000017500000001044511661521733021252 0ustar terceiroterceiro#!/usr/bin/env ruby require 'test/test_setup' class TestDemeterMocking < Test::Unit::TestCase include FlexMock::TestCase def test_demeter_mocking m = flexmock("A") m.should_receive("children.first").and_return(:first) assert_kind_of FlexMock, m assert_kind_of FlexMock, m.children assert_equal :first, m.children.first end def test_demeter_mocking_with_operators m = flexmock("A") m.should_receive("children.+@.last").and_return(:value) assert_kind_of FlexMock, m assert_kind_of FlexMock, m.children assert_kind_of FlexMock, + m.children assert_equal :value, (+ m.children).last end def test_demeter_mocking_with_multiple_operators m = flexmock("A") m.should_receive("+@.-@.~").and_return(:value) assert_equal :value, ~-+m end def test_multiple_demeter_mocks_on_same_branch_is_ok m = flexmock("A") m.should_receive("child.x.y.z.first").and_return(:first) m.should_receive("child.x.y.z.last").and_return(:last) assert_equal :first, m.child.x.y.z.first assert_equal :last, m.child.x.y.z.last end def test_multi_level_deep_demeter_violation a = flexmock("a") a.should_receive("b.c.d.e.f.g.h.i.j.k").and_return(:xyzzy) assert_equal :xyzzy, a.b.c.d.e.f.g.h.i.j.k end def test_final_method_can_have_multiple_expecations a = flexmock("a") a.should_receive("b.c.d.last").with(1).and_return(:one).once a.should_receive("b.c.d.last").with(2).and_return(:two).once assert_equal :one, a.b.c.d.last(1) assert_equal :two, a.b.c.d.last(2) end def test_conflicting_mock_declarations_raises_an_error m = flexmock("A") ex = assert_raise(FlexMock::UsageError) do m.should_receive("child").and_return(:xyzzy) m.should_receive("child.other").and_return(:other) m.child.other end assert_match(/conflicting/i, ex.message) assert_match(/mock\s+declaration/i, ex.message) assert_match(/child/i, ex.message) end def test_conflicting_mock_declarations_in_reverse_order_does_not_raise_error # Not all conflicting definitions can be detected. m = flexmock("A") assert_failure() do m.should_receive("child.other").and_return(:other) m.should_receive("child").and_return(:xyzzy) assert_equal :xyzzy, m.child.other end end def test_preestablishing_existing_mock_is_ok engine = flexmock("engine") car = flexmock("A") car.should_receive(:engine).and_return(engine) car.should_receive("engine.cylinder").and_return(:cyl) assert_equal :cyl, car.engine.cylinder end def test_quick_defs_can_use_demeter_mocking a = flexmock("a") a.should_receive("b.c.d.x").and_return(:x) a.should_receive("b.c.d.y").and_return(:y) a.should_receive("b.c.d.z").and_return(:z) assert_equal :x, a.b.c.d.x assert_equal :y, a.b.c.d.y assert_equal :z, a.b.c.d.z end def test_quick_defs_can_use_demeter_mocking_two a = flexmock("a", "b.c.d.xx" => :x, "b.c.d.yy" => :y, "b.c.d.zz" => :z) assert_equal :x, a.b.c.d.xx assert_equal :y, a.b.c.d.yy assert_equal :z, a.b.c.d.zz end def test_errors_on_ill_formed_method_names m = flexmock("a") [ 'a(2)', '0a', 'a-b', 'a b', ' ', 'a ', ' b', 'a!b', "a?b", 'a=b' ].each do |method| assert_raise FlexMock::UsageError do m.should_receive(method) end end end def test_no_errors_on_well_formed_method_names m = flexmock("a") [ 'a', 'a?', 'a!', 'a=', 'z0', 'save!' ].each do |method| assert_nothing_raised do m.should_receive(method) end end end def test_readme_example_1 cog = flexmock("cog") cog.should_receive(:turn).once.and_return(:ok).mock joint = flexmock("gear", :cog => cog) axle = flexmock("axle", :universal_joint => joint) chassis = flexmock("chassis", :axle => axle) car = flexmock("car", :chassis => chassis) assert_equal :ok, car.chassis.axle.universal_joint.cog.turn end def test_readme_example_2 car = flexmock("car") car.should_receive("chassis.axle.universal_joint.cog.turn" => :ok).once assert_equal :ok, car.chassis.axle.universal_joint.cog.turn end def test_readme_example_3 car = flexmock("car") car.should_receive("chassis.axle.universal_joint.cog.turn").once. and_return(:ok) assert_equal :ok, car.chassis.axle.universal_joint.cog.turn end end flexmock-0.9.0/test/default_framework_adapter_test.rb0000755000175000017500000000202311661521733023313 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require "test/test_setup" class TestFlexmockDefaultFrameworkAdapter < Test::Unit::TestCase def setup @adapter = FlexMock::DefaultFrameworkAdapter.new end def test_assert_block_raises_exception assert_raise(FlexMock::DefaultFrameworkAdapter::AssertionFailedError) { @adapter.assert_block("failure message") { false } } end def test_assert_block_doesnt_raise_exception @adapter.assert_block("failure message") { true } end def test_assert_equal_doesnt_raise_exception @adapter.assert_equal("a", "a", "no message") end def test_assert_equal_can_fail assert_raise(FlexMock::DefaultFrameworkAdapter::AssertionFailedError) { @adapter.assert_equal("a", "b", "a should not equal b") } end end flexmock-0.9.0/test/container_methods_test.rb0000755000175000017500000000617111661521733021627 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require "test/test_setup" # These tests exercise the interface used to define mocks class TestFlexmockContainerMethods < Test::Unit::TestCase include FlexMock::TestCase def test_simple_mock_creation mock = flexmock mock.should_receive(:hi).once.and_return(:lo) assert_equal :lo, mock.hi end def test_mock_with_name mock = flexmock("Danny") mock.should_receive(:xxx).with(1) ex = assert_raise(assertion_failed_error) { mock.xxx } assert_match(/Danny/, ex.message) end def test_mock_with_symbol_name mock = flexmock(:Danny) mock.should_receive(:xxx).with(1) ex = assert_raise(assertion_failed_error) { mock.xxx } assert_match(/Danny/, ex.message) end def test_mock_with_hash mock = flexmock(:hi => :lo, :good => :bye) assert_equal :lo, mock.hi assert_equal :bye, mock.good end def test_mock_with_name_and_hash mock = flexmock("Danny", :hi => :lo, :good => :bye) mock.should_receive(:xxx).with(1) assert_equal :lo, mock.hi assert_equal :bye, mock.good ex = assert_raise(assertion_failed_error) { mock.xxx } assert_match(/Danny/, ex.message) end def test_mock_with_name_hash_and_block mock = flexmock("Danny", :hi => :lo, :good => :bye) do |m| m.should_receive(:one).and_return(1) end assert_equal 1, mock.one assert_equal :lo, mock.hi end def test_basic_stub fido = Object.new mock = flexmock(fido) mock.should_receive(:wag).and_return(:happy) assert_equal :happy, fido.wag end def test_basic_stub_with_name fido = Object.new mock = flexmock(fido, "Danny") mock.should_receive(:xxx).with(1).and_return(:happy) ex = assert_raise(assertion_failed_error) { fido.xxx } assert_match(/Danny/, ex.message) end def test_stub_with_quick_definitions fido = Object.new flexmock(fido, :wag => :happy) assert_equal :happy, fido.wag end def test_stub_with_name_quick_definitions fido = Object.new mock = flexmock(fido, "Danny", :wag => :happy) mock.should_receive(:xxx).with(1).and_return(:happy) ex = assert_raise(assertion_failed_error) { fido.xxx } assert_match(/Danny/, ex.message) assert_equal :happy, fido.wag end def test_stubs_are_auto_verified fido = Object.new mock = flexmock(fido) mock.should_receive(:hi).once assert_raise(assertion_failed_error) { flexmock_verify } end def test_stubbing_a_string s = "hello" flexmock(:base, s, :length => 2) assert_equal 2, s.length end def test_multiple_stubs_work_with_same_partial_mock_proxy obj = Object.new mock1 = flexmock(obj) mock2 = flexmock(obj) assert_equal mock1, mock2 end def test_multiple_stubs_layer_behavior obj = Object.new flexmock(obj, :hi => :lo) flexmock(obj, :high => :low) assert_equal :lo, obj.hi assert_equal :low, obj.high end end flexmock-0.9.0/test/aliasing_test.rb0000644000175000017500000000234211661521733017702 0ustar terceiroterceiro#!/usr/bin/env ruby require 'test/test_setup' class FlexMock module StubsAndExpects def expects(*args) result = should_receive(*args) result.at_least.once unless result.call_count_constrained? result end def stubs(*args) should_receive(*args) end end module MockContainer alias :mock :flexmock alias :stub :flexmock end include StubsAndExpects class PartialMockProxy include StubsAndExpects MOCK_METHODS << :stubs << :expects end end class AliasingTest < Test::Unit::TestCase include FlexMock::TestCase def test_mocking m = mock("a cute dog").expects(:pat).twice.and_return(:woof!).mock assert_equal :woof!, m.pat assert_equal :woof!, m.pat end def test_once_mocking mock("a cute dog").expects(:pat).and_return(:woof!).mock end def test_twice_mocking m = mock("a cute dog").expects(:pat).and_return(:woof!).twice.mock assert_raises(assertion_failed_error) { m.flexmock_verify } end def test_stubbing m = stub("a cute dog").expects(:pat).and_return(:woof!).mock assert_equal :woof!, m.pat end def test_partial obj = Object.new stub(obj).stubs(:wag).and_return(:tail) assert_equal :tail, obj.wag end end flexmock-0.9.0/lib/0000755000175000017500000000000011661521733014315 5ustar terceiroterceiroflexmock-0.9.0/lib/flexmock.rb0000644000175000017500000000054611661521733016457 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/base' require 'flexmock/test_unit_integration' flexmock-0.9.0/lib/flexmock/0000755000175000017500000000000011661521733016125 5ustar terceiroterceiroflexmock-0.9.0/lib/flexmock/version.rb0000644000175000017500000000023311661521733020135 0ustar terceiroterceiroclass FlexMock module Version NUMBERS = [ MAJOR = 0, MINOR = 9, BUILD = 0, ] end VERSION = Version::NUMBERS.join('.') end flexmock-0.9.0/lib/flexmock/validators.rb0000755000175000017500000000447211661521733020634 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/noop' class FlexMock #################################################################### # Base class for all the count validators. # class CountValidator def initialize(expectation, limit) @exp = expectation @limit = limit end # If the expectation has been called +n+ times, is it still # eligible to be called again? The default answer compares n to # the established limit. def eligible?(n) n < @limit end end #################################################################### # Validator for exact call counts. # class ExactCountValidator < CountValidator # Validate that the method expectation was called exactly +n+ # times. def validate(n) FlexMock.framework_adapter.assert_equal @limit, n, "method '#{@exp}' called incorrect number of times" end end #################################################################### # Validator for call counts greater than or equal to a limit. # class AtLeastCountValidator < CountValidator # Validate the method expectation was called no more than +n+ # times. def validate(n) FlexMock.framework_adapter.assert_block( "Method '#{@exp}' should be called at least #{@limit} times,\n" + "only called #{n} times") { n >= @limit } end # If the expectation has been called +n+ times, is it still # eligible to be called again? Since this validator only # establishes a lower limit, not an upper limit, then the answer # is always true. def eligible?(n) true end end #################################################################### # Validator for call counts less than or equal to a limit. # class AtMostCountValidator < CountValidator # Validate the method expectation was called at least +n+ times. def validate(n) FlexMock.framework_adapter.assert_block( "Method '#{@exp}' should be called at most #{@limit} times,\n" + "only called #{n} times") { n <= @limit } end end end flexmock-0.9.0/lib/flexmock/undefined.rb0000644000175000017500000000174011661521733020415 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ class FlexMock # Undefined is a self preserving undefined object. The result of # any interaction with the undefined object will be the undefined # object itself. class Undefined def method_missing(sym, *args, &block) self end def to_s "-UNDEFINED-" end def inspect to_s end def clone self end def <=>(other) self end def coerce(other) [FlexMock.undefined, FlexMock.undefined] end end # Single instance of undefined @undefined = Undefined.new # Undefined is normally available as FlexMock.undefined def self.undefined @undefined end class << Undefined private :new end end flexmock-0.9.0/lib/flexmock/test_unit_integration.rb0000755000175000017500000000302111661521733023072 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'test/unit' require 'flexmock/base' class FlexMock #################################################################### # Test::Unit::TestCase Integration. # # Include this module in any TestCase class in a Test::Unit test # suite to get integration with FlexMock. When this module is # included, the mock container methods (e.g. flexmock(), flexstub()) # will be available. # # Note: If you define a +teardown+ method in the test case, # dont' forget to invoke the +super+ method! Failure to # invoke super will cause all mocks to not be verified. # module TestCase include ArgumentTypes include MockContainer # Teardown the test case, verifying any mocks that might have been # defined in this test case. def teardown super flexmock_teardown end end #################################################################### # Adapter for adapting FlexMock to the Test::Unit framework. # class TestUnitFrameworkAdapter include Test::Unit::Assertions def assertion_failed_error defined?(Test::Unit::AssertionFailedError) ? Test::Unit::AssertionFailedError : MiniTest::Assertion end end @framework_adapter = TestUnitFrameworkAdapter.new end flexmock-0.9.0/lib/flexmock/test_unit.rb0000755000175000017500000000142111661521733020471 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/test_unit_integration' module Test module Unit class TestCase include FlexMock::ArgumentTypes include FlexMock::MockContainer # Alias the original teardown behavior for later use. alias :flexmock_original_teardown :teardown # Teardown the test case, verifying any mocks that might have been # defined in this test case. def teardown flexmock_teardown flexmock_original_teardown end end end end flexmock-0.9.0/lib/flexmock/rspec.rb0000755000175000017500000000162511661521733017575 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim.weirich@gmail.com). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/base' class FlexMock if defined?(::RSpec) SpecModule = RSpec else SpecModule = Spec end class RSpecFrameworkAdapter def assert_block(msg, &block) SpecModule::Expectations.fail_with(msg) unless yield end def assert_equal(a, b, msg=nil) message = msg || "Expected equal" assert_block(message + "\n<#{a}> expected, but was\n<#{b}>") { a == b } end class AssertionFailedError < StandardError; end def assertion_failed_error SpecModule::Expectations::ExpectationNotMetError end end @framework_adapter = RSpecFrameworkAdapter.new end flexmock-0.9.0/lib/flexmock/recorder.rb0000755000175000017500000000405411661521733020265 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/argument_types' class FlexMock #################################################################### # Translate arbitrary method calls into expectations on the given # mock object. # class Recorder include FlexMock::ArgumentTypes # Create a method recorder for the mock +mock+. def initialize(mock) @mock = mock @strict = false end # Place the record in strict mode. While recording expectations # in strict mode, the following will be true. # # * All expectations will be expected in the order they were # recorded. # * All expectations will be expected once. # * All arguments will be placed in exact match mode, # including regular expressions and class objects. # # Strict mode is usually used when giving the recorder to a known # good algorithm. Strict mode captures the exact sequence of # calls and validate that the code under test performs the exact # same sequence of calls. # # The recorder may exit strict mode via a # should_be_strict(false) call. Non-strict expectations # may be recorded at that point, or even explicit expectations # (using +should_receieve+) can be specified. # def should_be_strict(is_strict=true) @strict = is_strict end # Is the recorder in strict mode? def strict? @strict end # Record an expectation for receiving the method +sym+ with the # given arguments. def method_missing(sym, *args, &block) expectation = @mock.should_receive(sym).and_return(&block) if strict? args = args.collect { |arg| eq(arg) } expectation.with(*args).ordered.once else expectation.with(*args) end expectation end end end flexmock-0.9.0/lib/flexmock/rails.rb0000644000175000017500000000063111661521733017564 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ # Require the modules needed for rails oriented mocking. require 'flexmock' require 'flexmock/rails/view_mocking' flexmock-0.9.0/lib/flexmock/rails/0000755000175000017500000000000011661521733017237 5ustar terceiroterceiroflexmock-0.9.0/lib/flexmock/rails/view_mocking.rb0000644000175000017500000001173111661521733022250 0ustar terceiroterceirorequire 'flexmock' class FlexMock module MockContainer def rails_version Rails::VERSION::STRING end # Declare that the Rails controller under test should render the # named view. If a view template name is given, it will be an # error if the named view is not rendered during the execution of # the contoller action. If no template name is given, then the # any view may be rendered. If no view is actually rendered, then # an assertion failure will occur. # # def test_my_action_does_what_it_should # should_render_view 'show' # # get :show, :id => 1 # # assert_response :success # end # def should_render_view(template_name=nil) if rails_version <= '1.2.4' should_render_view_prior_version_124(template_name) elsif rails_version <= '2.0.0' should_render_view_after_version_124(template_name) elsif rails_version < '2.2' should_render_view_after_version_202(template_name) elsif rails_version < '2.3' should_render_view_22x(template_name) else should_render_view_23x(template_name) end end private # This version of should_render_view will work for Rails 1.2.4 # (and prehaps some number of prior versions). def should_render_view_prior_version_124(template_name) # :nodoc: view = flexmock("MockView") view.should_receive( :assigns => {}, :render_file => true, :render_partial => true, :first_render => "dummy_template" ) if template_name view.should_receive(:file_exists?).with(/#{template_name}$/).once. and_return(true) end view.should_receive(:file_exists?).with(any).and_return(true) view_class = flexmock("MockViewClasss") view_class.should_receive(:new).and_return(view) flexmock(@controller.class).should_receive(:view_class).once. and_return(view_class) end # This version of should_render_view will work with versions of # Rails after Version 1.2.4. def should_render_view_after_version_124(template_name) view = flexmock("MockView") view.should_receive( :assigns => {}, :render_file => true, :render_partial => true, :template_format => :dummy_format, :view_paths => :dummy_view_paths, :pick_template_extension => :dummy_extension ) if template_name view.should_receive(:file_exists?).with(/#{template_name}$/).once. and_return(true) end view.should_receive(:file_exists?).with(any).and_return(true) # The number of times this is called changes from version 1.2.6 # to 2.0. The important thing is that it is checked at least once. flexmock(@response).should_receive(:template).and_return(view). at_least.once end # This version of should_render_view will work with versions of # Rails at Version 2.0.2 and after def should_render_view_after_version_202(template_name) viewmock = flexmock("ViewMock") viewmock.should_receive( :assigns => {}, :pick_template_extension => ".html", :template_format =>nil, :view_paths => nil, :file_exists? => true, :first_render => "") if template_name viewmock.should_receive(:render_file).with(/\/#{template_name}$/, any, any). and_return(nil).once viewmock.should_receive(:render_file).and_return(nil) else viewmock.should_receive(:render_file).at_least.once.and_return(nil) end flexmock(ActionView::Base).should_receive(:new).and_return(viewmock) end # This version of should_render_view will work with versions of # Rails at Version 2.2.x. def should_render_view_22x(template_name) viewmock = flexmock("ViewMock") viewmock.should_receive( :helpers => viewmock, :include => nil, :template_format =>nil, :render => "RENDERED TEXT", :assigns => {}) if template_name viewmock.should_receive(:_exempt_from_layout?).with(/\/#{template_name}$/). and_return(true).once viewmock.should_receive(:_exempt_from_layout?).and_return(true) else viewmock.should_receive(:_exempt_from_layout?).at_least.once.and_return(true) end flexmock(ActionView::Base).should_receive(:new).and_return(viewmock) end # This version of should_render_view will work with versions of # Rails at Version 2.3.x. def should_render_view_23x(template_name) viewmock = flexmock("ViewMock") viewmock.should_receive( :view_paths => viewmock, :render => "RENDERED TEXT") if template_name viewmock.should_receive(:find_template). with(/\/#{template_name}$/, any). and_return(FlexMock.undefined). at_least.once end viewmock.should_ignore_missing flexmock(ActionView::Base).should_receive(:new).and_return(viewmock) end end end flexmock-0.9.0/lib/flexmock/partial_mock.rb0000755000175000017500000002336411661521733021132 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/noop' class FlexMock # ######################################################################### # PartialMockProxy is used to mate the mock framework to an existing # object. The object is "enhanced" with a reference to a mock # object (stored in @flexmock_proxy). When the # +should_receive+ method is sent to the proxy, it overrides the # existing object's method by creating singleton method that # forwards to the mock. When testing is complete, PartialMockProxy # will erase the mocking infrastructure from the object being mocked # (e.g. remove instance variables and mock singleton methods). # class PartialMockProxy include Ordering attr_reader :mock # The following methods are added to partial mocks so that they # can act like a mock. MOCK_METHODS = [ :should_receive, :new_instances, :flexmock_get, :flexmock_teardown, :flexmock_verify ] # Initialize a PartialMockProxy object. def initialize(obj, mock, safe_mode) @obj = obj @mock = mock @method_definitions = {} @methods_proxied = [] unless safe_mode add_mock_method(:should_receive) MOCK_METHODS.each do |sym| unless @obj.respond_to?(sym) add_mock_method(sym) end end end end # Get the mock object for the partial mock. def flexmock_get @mock end # :call-seq: # should_receive(:method_name) # should_receive(:method1, method2, ...) # should_receive(:meth1 => result1, :meth2 => result2, ...) # # Declare that the partial mock should receive a message with the given # name. # # If more than one method name is given, then the mock object should # expect to receive all the listed melthods. If a hash of method # name/value pairs is given, then the each method will return the # associated result. Any expectations applied to the result of # +should_receive+ will be applied to all the methods defined in the # argument list. # # An expectation object for the method name is returned as the result of # this method. Further expectation constraints can be added by chaining # to the result. # # See Expectation for a list of declarators that can be used. def should_receive(*args) ContainerHelper.parse_should_args(@mock, args) do |sym| unless @methods_proxied.include?(sym) hide_existing_method(sym) end ex = @mock.should_receive(sym) ex.mock = self ex end end def add_mock_method(method_name) stow_existing_definition(method_name) sclass.module_eval do define_method(method_name) { |*args, &block| proxy = instance_variable_get("@flexmock_proxy") if proxy.nil? fail "Missing FlexMock proxy " + "(for method_name=#{method_name.inspect}, self=\#{self})" end proxy.send(method_name, *args, &block) } end end # :call-seq: # new_instances.should_receive(...) # new_instances { |instance| instance.should_receive(...) } # # new_instances is a short cut method for overriding the behavior of any # new instances created via a mocked class object. # # By default, new_instances will mock the behaviour of the :new # method. If you wish to mock a different set of class methods, # just pass a list of symbols to as arguments. (previous versions # also mocked :allocate by default. If you need :allocate to be # mocked, just request it explicitly). # # For example, to stub only objects created by :make (and not # :new), use: # # flexmock(ClassName).new_instances(:make).should_receive(...) # def new_instances(*allocators, &block) fail ArgumentError, "new_instances requires a Class to stub" unless Class === @obj allocators = [:new] if allocators.empty? result = ExpectationRecorder.new allocators.each do |allocate_method| check_allocate_method(allocate_method) # HACK: Without the following lambda, Ruby 1.9 will not bind # the allocate_method parameter correctly. lambda { } self.should_receive(allocate_method).and_return { |*args| new_obj = invoke_original(allocate_method, args) mock = flexmock_container.flexmock(new_obj) block.call(mock) if block_given? result.apply(mock) new_obj } end result end # Invoke the original definition of method on the object supported by # the stub. def invoke_original(method, args) method_proc = @method_definitions[method] method_proc.call(*args) end private :invoke_original # Verify that the mock has been properly called. After verification, # detach the mocking infrastructure from the existing object. def flexmock_verify @mock.flexmock_verify end # Remove all traces of the mocking framework from the existing object. def flexmock_teardown if ! detached? @methods_proxied.each do |method_name| remove_current_method(method_name) restore_original_definition(method_name) end @obj.instance_variable_set("@flexmock_proxy", nil) @obj = nil end end # Forward to the mock's container. def flexmock_container @mock.flexmock_container end # Set the proxy's mock container. This set value is ignored # because the proxy always uses the container of its mock. def flexmock_container=(container) end # Forward the request for the expectation director to the mock. def flexmock_expectations_for(method_name) @mock.flexmock_expectations_for(method_name) end private def check_allocate_method(allocate_method) if allocate_method == :allocate && RUBY_VERSION >= "1.9" fail UsageError, "Cannot mock the allocation method using new_instances in Ruby 1.9" end end # The singleton class of the object. def sclass class << @obj; self; end end # Is the given method name a singleton method in the object we are # mocking? def singleton?(method_name) @obj.methods(false).include?(method_name.to_s) end # Hide the existing method definition with a singleton defintion # that proxies to our mock object. If the current definition is a # singleton, we need to record the definition and remove it before # creating our own singleton method. If the current definition is # not a singleton, all we need to do is override it with our own # singleton. def hide_existing_method(method_name) stow_existing_definition(method_name) define_proxy_method(method_name) end # Stow the existing method definition so that it can be recovered # later. def stow_existing_definition(method_name) @methods_proxied << method_name new_alias = create_alias_for_existing_method(method_name) if new_alias my_object = @obj @method_definitions[method_name] = Proc.new { |*args| block = nil if Proc === args.last block = args.last args = args[0...-1] end my_object.send(new_alias, *args, &block) } end remove_current_method(method_name) if singleton?(method_name) end # Create an alias for the existing +method_name+. Returns the new # alias name. If the aliasing process fails (because the method # doesn't really exist, then return nil. def create_alias_for_existing_method(method_name) begin new_alias = new_name(method_name) unless @obj.respond_to?(new_alias) sclass.class_eval do alias_method(new_alias, method_name) end end new_alias rescue NameError => _ # Alias attempt failed nil end end # Define a proxy method that forwards to our mock object. The # proxy method is defined as a singleton method on the object # being mocked. def define_proxy_method(method_name) if method_name.to_s =~ /=$/ eval_line = __LINE__ + 1 sclass.class_eval %{ def #{method_name}(*args, &block) instance_variable_get('@flexmock_proxy').mock.__send__(:#{method_name}, *args, &block) end }, __FILE__, eval_line else eval_line = __LINE__ + 1 sclass.class_eval %{ def #{method_name}(*args, &block) instance_variable_get('@flexmock_proxy').mock.#{method_name}(*args, &block) end }, __FILE__, eval_line _ = true # make rcov recognize the above eval is covered end end # Restore the original singleton defintion for method_name that # was saved earlier. def restore_original_definition(method_name) method_def = @method_definitions[method_name] if method_def the_alias = new_name(method_name) sclass.class_eval do alias_method(method_name, the_alias) end end end # Remove the current method if it is a singleton method of the # object being mocked. def remove_current_method(method_name) sclass.class_eval { remove_method(method_name) } end # Have we been detached from the existing object? def detached? @obj.nil? end # Generate a name to be used to alias the original behavior. def new_name(old_name) "flexmock_original_behavior_for_#{old_name}" end end end flexmock-0.9.0/lib/flexmock/ordering.rb0000644000175000017500000000300711661521733020263 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ class FlexMock # ################################################################# # The ordering module contains the methods and data structures used # to determine proper orderring of mocked calls. By providing the # functionality in a module, a individual mock object can order its # own calls, and the container can provide ordering at a global # level. module Ordering # Allocate the next available order number. def flexmock_allocate_order @flexmock_allocated_order ||= 0 @flexmock_allocated_order += 1 end # Hash of groups defined in this ordering. def flexmock_groups @flexmock_groups ||= {} end # Current order number in this ordering. def flexmock_current_order @flexmock_current_order ||= 0 end # Set the current order for this ordering. def flexmock_current_order=(value) @flexmock_current_order = value end def flexmock_validate_order(method_name, order_number) FlexMock.check("method #{method_name} called out of order " + "(expected order #{order_number}, was #{flexmock_current_order})") { order_number >= self.flexmock_current_order } self.flexmock_current_order = order_number end end end flexmock-0.9.0/lib/flexmock/noop.rb0000755000175000017500000000064011661521733017430 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ # No-op include file. Used as a kludge so that only the comments in the # core.rb file are applied to the FlexMock class. flexmock-0.9.0/lib/flexmock/mock_container.rb0000755000175000017500000003074611661521733021462 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/noop' require 'flexmock/argument_types' require 'flexmock/ordering' class FlexMock # ###################################################################### # Mock container methods # # Include this module in to get integration with FlexMock. When this module # is included, mocks may be created with a simple call to the +flexmock+ # method. Mocks created with via the method call will automatically be # verified in the teardown of the test case. # module MockContainer include Ordering # Do the flexmock specific teardown stuff. If you need finer control, # you can use either +flexmock_verify+ or +flexmock_close+. def flexmock_teardown flexmock_verify unless flexmock_test_has_failed? ensure flexmock_close end # Perform verification on all mocks in the container. def flexmock_verify flexmock_created_mocks.each do |m| m.flexmock_verify end end # List of mocks created in this container def flexmock_created_mocks @flexmock_created_mocks ||= [] end # Close all the mock objects in the container. Closing a mock object # restores any original behavior that was displaced by the mock. def flexmock_close flexmock_created_mocks.each do |m| m.flexmock_teardown end @flexmock_created_mocks = [] end # Create a mocking object in the FlexMock framework. The +flexmock+ # method has a number of options available, depending on just what kind of # mocking object your require. Mocks created via +flexmock+ will be # automatically verify during the teardown phase of your test framework. # # :call-seq: # flexmock() { |mock| ... } # flexmock(name) { |mock| ... } # flexmock(expect_hash) { |mock| ... } # flexmock(name, expect_hash) { |mock| ... } # flexmock(real_object) { |mock| ... } # flexmock(real_object, name) { |mock| ... } # flexmock(real_object, name, expect_hash) { |mock| ... } # flexmock(:base, string, name, expect_hash) { |mock| ... } # # Note: A plain flexmock() call without a block will return the # mock object (the object that interprets should_receive and its # brethern). A flexmock() call that _includes_ a block will return the # domain objects (the object that will interpret domain messages) since # the mock will be passed to the block for configuration. With regular # mocks, this distinction is unimportant because the mock object and the # domain object are the same object. However, with partial mocks, the # mock object is separation from the domain object. Keep that distinciton # in mind. # # name :: # Name of the mock object. If no name is given, "unknown" is used for # full mocks and "flexmock(real_object)" is used for partial # mocks. # # expect_hash :: # Hash table of method names and values. Each method/value pair is # used to setup a simple expectation so that if the mock object # receives a message matching an entry in the table, it returns # the associated value. No argument our call count constraints are # added. Using an expect_hash is identical to calling: # # mock.should_receive(method_name).and_return(value) # # for each of the method/value pairs in the hash. # # real_object :: # If a real object is given, then a partial mock is constructed # using the real_object as a base. Partial mocks (formally referred # to as stubs) behave as a mock object when an expectation is matched, # and otherwise will behave like the original object. This is useful # when you want to use a real object for testing, but need to mock out # just one or two methods. # # :base :: # Forces the following argument to be used as the base of a # partial mock object. This explicit tag is only needed if you # want to use a string or a symbol as the mock base (string and # symbols would normally be interpretted as the mock name). # # &block :: # If a block is given, then the mock object is passed to the block and # expectations may be configured within the block. When a block is given # for a partial mock, flexmock will return the domain object rather than # the mock object. # def flexmock(*args) name = nil quick_defs = {} domain_obj = nil safe_mode = false model_class = nil while ! args.empty? case args.first when :base, :safe safe_mode = (args.shift == :safe) domain_obj = args.shift when :model args.shift model_class = args.shift when String, Symbol name = args.shift.to_s when Hash quick_defs = args.shift else domain_obj = args.shift end end raise UsageError, "a block is required in safe mode" if safe_mode && ! block_given? if domain_obj mock = ContainerHelper.make_partial_proxy(self, domain_obj, name, safe_mode) result = domain_obj elsif model_class id = ContainerHelper.next_id result = mock = FlexMock.new("#{model_class}_#{id}", self) else result = mock = FlexMock.new(name || "unknown", self) end mock.should_receive(quick_defs) yield(mock) if block_given? flexmock_remember(mock) ContainerHelper.add_model_methods(mock, model_class, id) if model_class result end alias flexstub flexmock # Remember the mock object / stub in the mock container. def flexmock_remember(mocking_object) @flexmock_created_mocks ||= [] @flexmock_created_mocks << mocking_object mocking_object.flexmock_container = self mocking_object end private # In frameworks (e.g. MiniTest) passed? will return nil to # indicate the test isn't over yet. From our point of view we are # only interested if the test has actually failed, so we wrap the # raw call to passed? and handle accordingly. def flexmock_test_has_failed? passed? == false end end # ################################################################# # Helper methods for mock containers. MockContainer is a module # that is designed to be mixed into other classes, particularly # testing framework test cases. Since we don't want to pollute the # method namespace of the class that mixes in MockContainer, a # number of MockContainer methods were moved into ContainerHelper to # to isoloate the names. # class MockContainerHelper include FlexMock::ArgumentTypes # Return the next id for mocked models. def next_id @id_counter ||= 10000 @id_counter += 1 end # :call-seq: # parse_should_args(args) { |symbol| ... } # # This method provides common handling for the various should_receive # argument lists. It sorts out the differences between symbols, arrays and # hashes, and identifies the method names specified by each. As each # method name is identified, create a mock expectation for it using the # supplied block. def parse_should_args(mock, args, &block) # :nodoc: result = CompositeExpectation.new args.each do |arg| case arg when Hash arg.each do |k,v| exp = build_demeter_chain(mock, k, &block).and_return(v) result.add(exp) end when Symbol, String result.add(build_demeter_chain(mock, arg, &block)) end end result end # Automatically add mocks for some common methods in ActiveRecord # models. def add_model_methods(mock, model_class, id) container = mock.flexmock_container mock_errors = container.flexmock("errors") mock_errors.should_receive(:count).and_return(0).by_default mock_errors.should_receive(:full_messages).and_return([]).by_default mock.should_receive(:id).and_return(id).by_default mock.should_receive(:to_params).and_return(id.to_s).by_default mock.should_receive(:new_record?).and_return(false).by_default mock.should_receive(:class).and_return(model_class).by_default mock.should_receive(:errors).and_return(mock_errors).by_default # HACK: Ruby 1.9 needs the following lambda so that model_class # is correctly bound below. lambda { } mock.should_receive(:is_a?).with(any).and_return { |other| other == model_class }.by_default mock.should_receive(:instance_of?).with(any).and_return { |other| other == model_class }.by_default mock.should_receive(:kind_of?).with(any).and_return { |other| model_class.ancestors.include?(other) }.by_default end # Create a PartialMockProxy for the given object. Use +name+ as # the name of the mock object. def make_partial_proxy(container, obj, name, safe_mode) name ||= "flexmock(#{obj.class.to_s})" if !obj.instance_variable_defined?("@flexmock_proxy") || obj.instance_variable_get("@flexmock_proxy").nil? mock = FlexMock.new(name, container) proxy = PartialMockProxy.new(obj, mock, safe_mode) obj.instance_variable_set("@flexmock_proxy", proxy) end obj.instance_variable_get("@flexmock_proxy") end private # Build the chain of mocks for demeter style mocking. # # Warning: Nasty code ahead. # # This method builds a chain of mocks to support demeter style # mocking. Given a mock chain of "first.second.third.last", we # must build a chain of mock methods that return the next mock in # the chain. The expectation for the last method of the chain is # returned as the result of the method. # # Things to consider: # # (1) The expectation for the "first" method must be created by # the proper mechanism, which is supplied by the block parameter # "block". In other words, first expectation is created by # calling the block. (This allows us to create expectations on # both pure mocks and partial mocks, with the block handling the # details). # # (2) Although the first mock is arbitrary, the remaining mocks in # the chain will always be pure mocks created specifically for # this purpose. # # (3) The expectations for all methods but the last in the chain # will be setup to expect no parameters and to return the next # mock in the chain. # # (4) It could very well be the case that several demeter chains # will be defined on a single mock object, and those chains could # share some of the same methods (e.g. "mock.one.two.read" and # "mock.one.two.write" both share the methods "one" and "two"). # It is important that the shared methods return the same mocks in # both chains. # def build_demeter_chain(mock, arg, &block) container = mock.flexmock_container names = arg.to_s.split('.') check_method_names(names) exp = nil next_exp = lambda { |n| block.call(n) } loop do method_name = names.shift.to_sym exp = mock.flexmock_find_expectation(method_name) need_new_exp = exp.nil? || names.empty? exp = next_exp.call(method_name) if need_new_exp break if names.empty? if need_new_exp mock = container.flexmock("demeter_#{method_name}") exp.with_no_args.and_return(mock) else mock = exp._return_value([]) end check_proper_mock(mock, method_name) next_exp = lambda { |n| mock.should_receive(n) } end exp end # Check that the given mock is a real FlexMock mock. def check_proper_mock(mock, method_name) unless mock.kind_of?(FlexMock) fail FlexMock::UsageError, "Conflicting mock declaration for '#{method_name}' in demeter style mock" end end METHOD_NAME_RE = /^([A-Za-z_][A-Za-z0-9_]*[=!?]?|\[\]=?||\*\*|<<|>>|<=>|[<>=]=|=~|===|[-+]@|[-+\*\/%&^|<>~`])$/ # Check that all the names in the list are valid method names. def check_method_names(names) names.each do |name| fail FlexMock::UsageError, "Ill-formed method name '#{name}'" if name !~ METHOD_NAME_RE end end end ContainerHelper = MockContainerHelper.new end flexmock-0.9.0/lib/flexmock/expectation_director.rb0000755000175000017500000000507411661521733022701 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/noop' require 'flexmock/errors' class FlexMock #################################################################### # The expectation director is responsible for routing calls to the # correct expectations for a given argument list. # class ExpectationDirector # Create an ExpectationDirector for a mock object. def initialize(sym) @sym = sym @expectations = [] @defaults = [] @expected_order = nil end # Invoke the expectations for a given set of arguments. # # First, look for an expectation that matches the arguments and # is eligible to be called. Failing that, look for a expectation # that matches the arguments (at this point it will be ineligible, # but at least we will get a good failure message). Finally, # check for expectations that don't have any argument matching # criteria. def call(*args) exp = find_expectation(*args) FlexMock.check("no matching handler found for " + FlexMock.format_args(@sym, args)) { ! exp.nil? } exp.verify_call(*args) end # Append an expectation to this director. def <<(expectation) @expectations << expectation end # Find an expectation matching the given arguments. def find_expectation(*args) # :nodoc: if @expectations.empty? find_expectation_in(@defaults, *args) else find_expectation_in(@expectations, *args) end end # Do the post test verification for this director. Check all the # expectations. Only check the default expecatations if there are # no non-default expectations. def flexmock_verify # :nodoc: (@expectations.empty? ? @defaults : @expectations).each do |exp| exp.flexmock_verify end end # Move the last defined expectation a default. def defaultify_expectation(exp) # :nodoc: last_exp = @expectations.last if last_exp != exp fail UsageError, "Cannot make a previously defined expection into a default" end @expectations.pop @defaults << exp end private def find_expectation_in(expectations, *args) expectations.find { |e| e.match_args(args) && e.eligible? } || expectations.find { |e| e.match_args(args) } end end end flexmock-0.9.0/lib/flexmock/expectation.rb0000755000175000017500000003441511661521733021007 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/noop' class FlexMock #################################################################### # An Expectation is returned from each +should_receive+ message sent # to mock object. Each expectation records how a message matching # the message name (argument to +should_receive+) and the argument # list (given by +with+) should behave. Mock expectations can be # recorded by chaining the declaration methods defined in this # class. # # For example: # # mock.should_receive(:meth).with(args).and_returns(result) # class Expectation attr_reader :expected_args, :order_number attr_accessor :mock # Create an expectation for a method named +sym+. def initialize(mock, sym) @mock = mock @sym = sym @expected_args = nil @count_validators = [] @count_validator_class = ExactCountValidator @actual_count = 0 @return_value = nil @return_queue = [] @yield_queue = [] @order_number = nil @global_order_number = nil @globally = nil end def to_s FlexMock.format_args(@sym, @expected_args) end # Verify the current call with the given arguments matches the # expectations recorded in this object. def verify_call(*args) validate_order @actual_count += 1 perform_yielding(args) return_value(args) end # Public return value (odd name to avoid accidental use as a # constraint). def _return_value(args) # :nodoc: return_value(args) end # Find the return value for this expectation. (private version) def return_value(args) case @return_queue.size when 0 block = lambda { |*a| @return_value } when 1 block = @return_queue.first else block = @return_queue.shift end block.call(*args) end private :return_value # Yield stored values to any blocks given. def perform_yielding(args) @return_value = nil unless @yield_queue.empty? block = args.last values = (@yield_queue.size == 1) ? @yield_queue.first : @yield_queue.shift if block && block.respond_to?(:call) @return_value = block.call(*values) else fail MockError, "No Block given to mock with 'and_yield' expectation" end end end private :perform_yielding # Is this expectation eligible to be called again? It is eligible # only if all of its count validators agree that it is eligible. def eligible? @count_validators.all? { |v| v.eligible?(@actual_count) } end # Is this expectation constrained by any call counts? def call_count_constrained? ! @count_validators.empty? end # Validate that the order def validate_order if @order_number @mock.flexmock_validate_order(to_s, @order_number) end if @global_order_number @mock.flexmock_container.flexmock_validate_order(to_s, @global_order_number) end end private :validate_order # Validate the correct number of calls have been made. Called by # the teardown process. def flexmock_verify @count_validators.each do |v| v.validate(@actual_count) end end # Does the argument list match this expectation's argument # specification. def match_args(args) # TODO: Rethink this: # return false if @expected_args.nil? return true if @expected_args.nil? return false if args.size != @expected_args.size (0...args.size).all? { |i| match_arg(@expected_args[i], args[i]) } end # Does the expected argument match the corresponding actual value. def match_arg(expected, actual) expected === actual || expected == actual || ( Regexp === expected && expected === actual.to_s ) end # Declare that the method should expect the given argument list. def with(*args) @expected_args = args self end # Declare that the method should be called with no arguments. def with_no_args with end # Declare that the method can be called with any number of # arguments of any type. def with_any_args @expected_args = nil self end # :call-seq: # and_return(value) # and_return(value, value, ...) # and_return { |*args| code } # # Declare that the method returns a particular value (when the # argument list is matched). # # * If a single value is given, it will be returned for all matching # calls. # * If multiple values are given, each value will be returned in turn for # each successive call. If the number of matching calls is greater # than the number of values, the last value will be returned for # the extra matching calls. # * If a block is given, it is evaluated on each call and its # value is returned. # # For example: # # mock.should_receive(:f).returns(12) # returns 12 # # mock.should_receive(:f).with(String). # returns an # returns { |str| str.upcase } # upcased string # # +returns+ is an alias for +and_return+. # def and_return(*args, &block) if block_given? @return_queue << block else args.each do |arg| @return_queue << lambda { |*a| arg } end end self end alias :returns :and_return # :nodoc: # Declare that the method returns and undefined object # (FlexMock.undefined). Since the undefined object will always # return itself for any message sent to it, it is a good "I don't # care" value to return for methods that are commonly used in # method chains. # # For example, if m.foo returns the undefined object, then: # # m.foo.bar.baz # # returns the undefined object without throwing an exception. # def and_return_undefined and_return(FlexMock.undefined) end alias :returns_undefined :and_return_undefined # :call-seq: # and_yield(value1, value2, ...) # # Declare that the mocked method is expected to be given a block # and that the block will be called with the values supplied to # yield. If the mock is called multiple times, mulitple # and_yield declarations can be used to supply different # values on each call. # # An error is raised if the mocked method is not called with a # block. def and_yield(*yield_values) @yield_queue << yield_values end alias :yields :and_yield # :call-seq: # and_raise(an_exception) # and_raise(SomeException) # and_raise(SomeException, args, ...) # # Declares that the method will raise the given exception (with # an optional message) when executed. # # * If an exception instance is given, then that instance will be # raised. # # * If an exception class is given, the exception raised with be # an instance of that class constructed with +new+. Any # additional arguments in the argument list will be passed to # the +new+ constructor when it is invoked. # # +raises+ is an alias for +and_raise+. # def and_raise(exception, *args) and_return { raise exception, *args } end alias :raises :and_raise # :call-seq: # and_throw(a_symbol) # and_throw(a_symbol, value) # # Declares that the method will throw the given symbol (with an # optional value) when executed. # # +throws+ is an alias for +and_throw+. # def and_throw(sym, value=nil) and_return { throw sym, value } end alias :throws :and_throw # Declare that the method may be called any number of times. def zero_or_more_times at_least.never end # Declare that the method is called +limit+ times with the # declared argument list. This may be modified by the +at_least+ # and +at_most+ declarators. def times(limit) @count_validators << @count_validator_class.new(self, limit) unless limit.nil? @count_validator_class = ExactCountValidator self end # Declare that the method is never expected to be called with the # given argument list. This may be modified by the +at_least+ and # +at_most+ declarators. def never times(0) end # Declare that the method is expected to be called exactly once # with the given argument list. This may be modified by the # +at_least+ and +at_most+ declarators. def once times(1) end # Declare that the method is expected to be called exactly twice # with the given argument list. This may be modified by the # +at_least+ and +at_most+ declarators. def twice times(2) end # Modifies the next call count declarator (+times+, +never+, # +once+ or +twice+) so that the declarator means the method is # called at least that many times. # # E.g. method f must be called at least twice: # # mock.should_receive(:f).at_least.twice # def at_least @count_validator_class = AtLeastCountValidator self end # Modifies the next call count declarator (+times+, +never+, # +once+ or +twice+) so that the declarator means the method is # called at most that many times. # # E.g. method f must be called no more than twice # # mock.should_receive(:f).at_most.twice # def at_most @count_validator_class = AtMostCountValidator self end # Declare that the given method must be called in order. All # ordered method calls must be received in the order specified by # the ordering of the +should_receive+ messages. Receiving a # methods out of the specified order will cause a test failure. # # If the user needs more fine control over ordering # (e.g. specifying that a group of messages may be received in any # order as long as they all come after another group of messages), # a _group_ _name_ may be specified in the +ordered+ calls. All # messages within the same group may be received in any order. # # For example, in the following, messages +flip+ and +flop+ may be # received in any order (because they are in the same group), but # must occur strictly after +start+ but before +end+. The message # +any_time+ may be received at any time because it is not # ordered. # # m = FlexMock.new # m.should_receive(:any_time) # m.should_receive(:start).ordered # m.should_receive(:flip).ordered(:flip_flop_group) # m.should_receive(:flop).ordered(:flip_flop_group) # m.should_receive(:end).ordered # def ordered(group_name=nil) if @globally @global_order_number = define_ordered(group_name, @mock.flexmock_container) else @order_number = define_ordered(group_name, @mock) end @globally = false self end # Modifier that changes the next ordered constraint to apply # globally across all mock objects in the container. def globally @globally = true self end # Helper method for defining ordered expectations. def define_ordered(group_name, ordering) fail UsageError, "Mock #{@mock.flexmock_name} is not in a container and cannot be globally ordered." if ordering.nil? if group_name.nil? result = ordering.flexmock_allocate_order elsif (num = ordering.flexmock_groups[group_name]) result = num else result = ordering.flexmock_allocate_order ordering.flexmock_groups[group_name] = result end result end private :define_ordered def by_default expectations = mock.flexmock_expectations_for(@sym) expectations.defaultify_expectation(self) if expectations end end ########################################################################## # A composite expectation allows several expectations to be grouped into a # single composite and then apply the same constraints to all expectations # in the group. class CompositeExpectation # Initialize the composite expectation. def initialize @expectations = [] end # Add an expectation to the composite. def add(expectation) @expectations << expectation end # Apply the constraint method to all expectations in the composite. def method_missing(sym, *args, &block) @expectations.each do |expectation| expectation.send(sym, *args, &block) end self end # The following methods return a value, so we make an arbitrary choice # and return the value for the first expectation in the composite. # Return the order number of the first expectation in the list. def order_number @expectations.first.order_number end # Return the associated mock object. def mock @expectations.first.mock end # Start a new method expectation. The following constraints will be # applied to the new expectation. def should_receive(*args, &block) @expectations.first.mock.should_receive(*args, &block) end # Return a string representations def to_s if @expectations.size > 1 "[" + @expectations.collect { |e| e.to_s }.join(', ') + "]" else @expectations.first.to_s end end end ########################################################################## # An expectation recorder records any expectations received and plays them # back on demand. This is used to collect the expectations in the blockless # version of the new_instances call. # class ExpectationRecorder # Initialize the recorder. def initialize @expectations = [] end # Save any incoming messages to be played back later. def method_missing(sym, *args, &block) @expectations << [sym, args, block] self end # Apply the recorded messages to the given object in a chaining fashion # (i.e. the result of the previous call is used as the target of the next # call). def apply(mock) obj = mock @expectations.each do |sym, args, block| obj = obj.send(sym, *args, &block) end end end end flexmock-0.9.0/lib/flexmock/errors.rb0000644000175000017500000000073411661521733017772 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/noop' class FlexMock # Error raised when flexmock is used incorrectly. class UsageError < ::RuntimeError end class MockError < ::RuntimeError end end flexmock-0.9.0/lib/flexmock/deprecated_methods.rb0000644000175000017500000000344611661521733022304 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ class Module def flexmock_deprecate(*method_names) method_names.each do |method_name| eval_line = __LINE__ + 1 module_eval %{ def #{method_name}(*args) $stderr.puts "#{method_name} is deprecated, use flex#{method_name} instead" flex#{method_name}(*args) end }, __FILE__, eval_line end end end # Deprecated Methods # ================== # # The following methods are no longer supported in FlexMock. Include # this file for legacy applications. # class FlexMock # Handle all messages denoted by +sym+ by calling the given block # and passing any parameters to the block. If we know exactly how # many calls are to be made to a particular method, we may check # that by passing in the number of expected calls as a second # paramter. def mock_handle(sym, expected_count=nil, &block) # :nodoc: $stderr.puts "mock_handle is deprecated, use the new should_receive interface instead." self.should_receive(sym).times(expected_count).returns(&block) end flexmock_deprecate :mock_verify, :mock_teardown, :mock_wrap class PartialMockProxy MOCK_METHODS << :any_instance # any_instance is present for backwards compatibility with version 0.5.0. # @deprecated def any_instance(&block) $stderr.puts "any_instance is deprecated, use new_instances instead." new_instances(&block) end end module Ordering flexmock_deprecate :mock_allocate_order, :mock_groups, :mock_current_order, :mock_validate_order end end flexmock-0.9.0/lib/flexmock/default_framework_adapter.rb0000755000175000017500000000130211661521733023652 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/noop' class FlexMock class DefaultFrameworkAdapter def assert_block(msg, &block) unless yield fail assertion_failed_error, msg end end def assert_equal(a, b, msg=nil) assert_block(msg || "Expected equal") { a == b } end class AssertionFailedError < StandardError; end def assertion_failed_error AssertionFailedError end end end flexmock-0.9.0/lib/flexmock/core_class_methods.rb0000755000175000017500000000446711661521733022330 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/noop' require 'flexmock/mock_container' class FlexMock class << self attr_reader :framework_adapter # Class method to make sure that verify is called at the end of a # test. One mock object will be created for each name given to # the use method. The mocks will be passed to the block as # arguments. If no names are given, then a single anonymous mock # object will be created. # # At the end of the use block, each mock object will be verified # to make sure the proper number of calls have been made. # # Usage: # # FlexMock.use("name") do |mock| # Creates a mock named "name" # mock.should_receive(:meth). # returns(0).once # end # mock is verified here # # NOTE: If you include FlexMock::TestCase into your test case # file, you can create mocks that will be automatically verified in # the test teardown by using the +flexmock+ method. # def use(*names) names = ["unknown"] if names.empty? container = UseContainer.new mocks = names.collect { |n| container.flexmock(n) } yield(*mocks) rescue Exception => _ container.got_exception = true raise ensure container.flexmock_teardown end # Class method to format a method name and argument list as a nice # looking string. def format_args(sym, args) # :nodoc: if args "#{sym}(#{args.collect { |a| a.inspect }.join(', ')})" else "#{sym}(*args)" end end # Check will assert the block returns true. If it doesn't, an # assertion failure is triggered with the given message. def check(msg, &block) # :nodoc: FlexMock.framework_adapter.assert_block(msg, &block) end end # Container object to be used by the FlexMock.use method. class UseContainer include MockContainer attr_accessor :got_exception def initialize @got_exception = false end def passed? ! got_exception end end end flexmock-0.9.0/lib/flexmock/core.rb0000755000175000017500000001436211661521733017413 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/errors' require 'flexmock/composite' require 'flexmock/ordering' ###################################################################### # FlexMock is a flexible mock object framework for supporting testing. # # FlexMock has a simple interface that's easy to remember, and leaves # the hard stuff to all those other mock object implementations. # # Basic Usage: # # m = flexmock("name") # m.should_receive(:upcase).with("stuff"). # and_return("STUFF") # m.should_receive(:downcase).with(String). # and_return { |s| s.downcase }.once # # With Test::Unit Integration: # # class TestSomething < Test::Unit::TestCase # include FlexMock::TestCase # # def test_something # m = flexmock("name") # m.should_receive(:hi).and_return("Hello") # m.hi # end # end # # Note: When using Test::Unit integeration, don't forget to include # FlexMock::TestCase. Also, if you override +teardown+, make sure you # call +super+. # class FlexMock include Ordering attr_reader :flexmock_name attr_accessor :flexmock_container # Create a FlexMock object with the given name. The name is used in # error messages. If no container is given, create a new, one-off # container for this mock. def initialize(name="unknown", container=nil) @flexmock_name = name @expectations = Hash.new @ignore_missing = false @verified = false container = UseContainer.new if container.nil? container.flexmock_remember(self) end # Return the inspection string for a mock. def inspect "" end # Verify that each method that had an explicit expected count was # actually called that many times. def flexmock_verify return if @verified @verified = true flexmock_wrap do @expectations.each do |sym, handler| handler.flexmock_verify end end end # Teardown and infrastructure setup for this mock. def flexmock_teardown end # Ignore all undefined (missing) method calls. def should_ignore_missing @ignore_missing = true end alias mock_ignore_missing should_ignore_missing def by_default @last_expectation.by_default self end # Handle missing methods by attempting to look up a handler. def method_missing(sym, *args, &block) flexmock_wrap do if handler = @expectations[sym] args << block if block_given? handler.call(*args) elsif @ignore_missing FlexMock.undefined else super(sym, *args, &block) end end end # Save the original definition of respond_to? for use a bit later. alias flexmock_respond_to? respond_to? # Override the built-in respond_to? to include the mocked methods. def respond_to?(sym, *args) super || (@expectations[sym] ? true : @ignore_missing) end # Find the mock expectation for method sym and arguments. def flexmock_find_expectation(method_name, *args) # :nodoc: exp = @expectations[method_name] exp ? exp.find_expectation(*args) : nil end # Return the expectation director for a method name. def flexmock_expectations_for(method_name) # :nodoc: @expectations[method_name] end # Override the built-in +method+ to include the mocked methods. def method(sym) @expectations[sym] || super rescue NameError => ex if @ignore_missing proc { FlexMock.undefined } else raise ex end end # :call-seq: # mock.should_receive(:method_name) # mock.should_receive(:method1, method2, ...) # mock.should_receive(:meth1 => result1, :meth2 => result2, ...) # # Declare that the mock object should receive a message with the given name. # # If more than one method name is given, then the mock object should expect # to receive all the listed melthods. If a hash of method name/value pairs # is given, then the each method will return the associated result. Any # expectations applied to the result of +should_receive+ will be applied to # all the methods defined in the argument list. # # An expectation object for the method name is returned as the result of # this method. Further expectation constraints can be added by chaining to # the result. # # See Expectation for a list of declarators that can be used. # def should_receive(*args) @last_expectation = ContainerHelper.parse_should_args(self, args) do |sym| @expectations[sym] ||= ExpectationDirector.new(sym) result = Expectation.new(self, sym) @expectations[sym] << result override_existing_method(sym) if flexmock_respond_to?(sym) result end @last_expectation end # Declare that the mock object should expect methods by providing a # recorder for the methods and having the user invoke the expected # methods in a block. Further expectations may be applied the # result of the recording call. # # Example Usage: # # mock.should_expect do |record| # record.add(Integer, 4) { |a, b| # a + b # }.at_least.once # def should_expect yield Recorder.new(self) end private # Wrap a block of code so the any assertion errors are wrapped so # that the mock name is added to the error message . def flexmock_wrap(&block) yield rescue FlexMock.framework_adapter.assertion_failed_error => ex raise FlexMock.framework_adapter.assertion_failed_error, "in mock '#{@flexmock_name}': #{ex.message}", ex.backtrace end # Override the existing definition of method +sym+ in the mock. # Most methods depend on the method_missing trick to be invoked. # However, if the method already exists, it will not call # method_missing. This method defines a singleton method on the # mock to explicitly invoke the method_missing logic. def override_existing_method(sym) sclass.class_eval <<-EOS def #{sym}(*args, &block) method_missing(:#{sym}, *args, &block) end EOS end # Return the singleton class of the mock object. def sclass class << self; self; end end end require 'flexmock/core_class_methods' flexmock-0.9.0/lib/flexmock/composite.rb0000755000175000017500000000023011661521733020452 0ustar terceiroterceiro#!/usr/bin/env ruby # # Created by Jim Weirich on 2007-04-14. # Copyright (c) 2007. All rights reserved. require 'flexmock/noop' class FlexMock endflexmock-0.9.0/lib/flexmock/base.rb0000755000175000017500000000127011661521733017367 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/core' require 'flexmock/default_framework_adapter' require 'flexmock/expectation_director' require 'flexmock/expectation' require 'flexmock/argument_matchers' require 'flexmock/argument_types' require 'flexmock/validators' require 'flexmock/recorder' require 'flexmock/mock_container' require 'flexmock/partial_mock' require 'flexmock/undefined' require 'flexmock/deprecated_methods' flexmock-0.9.0/lib/flexmock/argument_types.rb0000755000175000017500000000265411661521733021532 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/argument_matchers' class FlexMock #################################################################### # Include this module in your test class if you wish to use the +eq+ # and +any+ argument matching methods without a prefix. (Otherwise # use FlexMock.any and FlexMock.eq(obj). # module ArgumentTypes # Return an argument matcher that matches any argument. def any ANY end # Return an argument matcher that only matches things equal to # (==) the given object. def eq(obj) EqualMatcher.new(obj) end # Return an argument matcher that matches any object, that when # passed to the supplied block, will cause the block to return # true. def on(&block) ProcMatcher.new(&block) end # Return an argument matcher that matches a hash with the given # entries. def hsh(hash) HashMatcher.new(hash) end # Return an argument matcher that matches any object that # implementes (i.e. responds to) the given method list. def ducktype(*methods) DuckMatcher.new(methods) end end extend ArgumentTypes end flexmock-0.9.0/lib/flexmock/argument_matchers.rb0000755000175000017500000000350111661521733022164 0ustar terceiroterceiro#!/usr/bin/env ruby #--- # Copyright 2003-2011 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ require 'flexmock/noop' class FlexMock #################################################################### # Match any object class AnyMatcher def ===(target) true end def inspect "ANY" end end #################################################################### # Match only things that are equal. class EqualMatcher def initialize(obj) @obj = obj end def ===(target) @obj == target end def inspect "==(#{@obj.inspect})" end end ANY = AnyMatcher.new #################################################################### # Match only things where the block evaluates to true. class ProcMatcher def initialize(&block) @block = block end def ===(target) @block.call(target) end def inspect "on{...}" end end #################################################################### # Match only things where the block evaluates to true. class HashMatcher def initialize(hash) @hash = hash end def ===(target) @hash.all? { |k, v| target[k] == v } end def inspect "hsh(#{@hash.inspect})" end end #################################################################### # Match only things where the block evaluates to true. class DuckMatcher def initialize(methods) @methods = methods end def ===(target) @methods.all? { |m| target.respond_to?(m) } end def inspect "ducktype(#{@methods.map{|m| m.inspect}.join(',')})" end end end flexmock-0.9.0/TAGS0000644000175000017500000013771711661521733014250 0ustar terceiroterceiro doc/jamis.rb,43 module RDocRDoc1,0 module PagePage2,12 install.rb,29 def indir(newdir)indir7,68 lib/flexmock/argument_matchers.rb,722 class FlexMockFlexMock14,319 class AnyMatcherAnyMatcher17,426 def ===(target)===18,445 def inspectinspect21,484 class EqualMatcherEqualMatcher28,636 def initialize(obj)initialize29,657 def ===(target)===32,706 def inspectinspect35,755 class ProcMatcherProcMatcher44,966 def initialize(&block)initialize45,986 def ===(target)===48,1042 def inspectinspect51,1096 class HashMatcherHashMatcher58,1271 def initialize(hash)initialize59,1291 def ===(target)===62,1343 def inspectinspect65,1414 class DuckMatcherDuckMatcher72,1603 def initialize(methods)initialize73,1623 def ===(target)===76,1684 def inspectinspect79,1762 lib/flexmock/argument_types.rb,228 class FlexMockFlexMock14,331 module ArgumentTypesArgumentTypes21,624 def anyany23,707 def eq(obj)eq29,834 def on(&block)on36,1034 def hsh(hash)hsh42,1175 def ducktype(*methods)ducktype48,1352 lib/flexmock/base.rb,0 lib/flexmock/composite.rb,30 class FlexMockFlexMock8,133 lib/flexmock/core.rb,900 class FlexMockFlexMock46,1270 def initialize(name="unknown", container=nil)initialize55,1540 def inspectinspect65,1834 def flexmock_verifyflexmock_verify71,1994 def flexmock_teardownflexmock_teardown82,2235 def should_ignore_missingshould_ignore_missing86,2315 def by_defaultby_default91,2427 def method_missing(sym, *args, &block)method_missing97,2556 def respond_to?(sym, *args)respond_to?114,3028 def flexmock_find_expectation(method_name, *args) # :nodoc:flexmock_find_expectation119,3184 def flexmock_expectations_for(method_name) # :nodoc:flexmock_expectations_for125,3389 def method(sym)method130,3548 def should_receive(*args)should_receive159,4587 def should_expectshould_expect182,5330 def flexmock_wrap(&block)flexmock_wrap190,5520 def override_existing_method(sym)override_existing_method204,6075 def sclasssclass213,6295 lib/flexmock/core_class_methods.rb,289 class FlexMockFlexMock15,352 def use(*names)use39,1293 def format_args(sym, args) # :nodoc:format_args53,1691 def check(msg, &block) # :nodoc:check63,1992 class UseContainerUseContainer70,2165 def initializeinitialize75,2247 def passed?passed?79,2304 lib/flexmock/default_framework_adapter.rb,345 class FlexMockFlexMock14,318 class DefaultFrameworkAdapterDefaultFrameworkAdapter15,333 def assert_block(msg, &block)assert_block16,365 def assert_equal(a, b, msg=nil)assert_equal22,478 class AssertionFailedError < StandardError; endAssertionFailedError26,578 def assertion_failed_errorassertion_failed_error27,630 lib/flexmock/deprecated_methods.rb,340 class ModuleModule13,295 def flexmock_deprecate(*method_names)flexmock_deprecate14,308 class FlexMockFlexMock33,808 def mock_handle(sym, expected_count=nil, &block) # :nodoc:mock_handle40,1106 class PartialMockProxyPartialMockProxy47,1396 def any_instance(&block)any_instance53,1553 module OrderingOrdering59,1701 lib/flexmock/errors.rb,137 class FlexMockFlexMock14,319 class UsageError < ::RuntimeErrorUsageError17,387 class MockError < ::RuntimeErrorMockError20,430 lib/flexmock/expectation.rb,2059 class FlexMockFlexMock14,318 class ExpectationExpectation28,851 def initialize(mock, sym)initialize34,997 def to_sto_s49,1359 def verify_call(*args)verify_call55,1541 def _return_value(args) # :nodoc:_return_value64,1761 def return_value(args)return_value69,1901 def perform_yielding(args)perform_yielding83,2229 def eligible?eligible?99,2814 def call_count_constrained?call_count_constrained?104,2963 def validate_ordervalidate_order109,3067 def flexmock_verifyflexmock_verify121,3442 def match_args(args)match_args129,3639 def match_arg(expected, actual)match_arg138,3985 def with(*args)with145,4214 def with_no_argswith_no_args151,4348 def with_any_argswith_any_args157,4481 def and_return(*args, &block)and_return188,5490 def and_return_undefinedand_return_undefined212,6207 def and_yield(*yield_values)and_yield228,6776 def and_raise(exception, *args)and_raise252,7529 def and_throw(sym, value=nil)and_throw266,7894 def zero_or_more_timeszero_or_more_times272,8069 def times(limit)times279,8292 def nevernever288,8639 def onceonce295,8854 def twicetwice302,9069 def at_leastat_least314,9395 def at_mostat_most327,9774 def ordered(group_name=nil)ordered356,11043 def globallyglobally368,11423 def define_ordered(group_name, ordering)define_ordered374,11538 def by_defaultby_default388,12036 class CompositeExpectationCompositeExpectation399,12443 def initializeinitialize402,12517 def add(expectation)add407,12613 def method_missing(sym, *args, &block)method_missing412,12754 def order_numberorder_number423,13129 def mockmock428,13239 def should_receive(*args, &block)should_receive434,13403 def to_sto_s439,13549 class ExpectationRecorderExpectationRecorder453,14007 def initializeinitialize456,14067 def method_missing(sym, *args, &block)method_missing461,14178 def apply(mock)apply469,14450 lib/flexmock/expectation_director.rb,483 class FlexMockFlexMock15,344 class ExpectationDirectorExpectationDirector20,555 def initialize(sym)initialize23,639 def call(*args)call38,1187 def <<(expectation)<<46,1440 def find_expectation(*args) # :nodoc:find_expectation51,1564 def flexmock_verify # :nodoc:flexmock_verify62,1938 def defaultify_expectation(exp) # :nodoc:defaultify_expectation69,2149 def find_expectation_in(expectations, *args)find_expectation_in81,2430 lib/flexmock/mock_container.rb,944 class FlexMockFlexMock16,380 module MockContainerMockContainer26,781 def flexmock_teardownflexmock_teardown31,965 def flexmock_verifyflexmock_verify40,1208 def flexmock_created_mocksflexmock_created_mocks49,1448 def flexmock_closeflexmock_close55,1668 def flexmock(*args)flexmock123,4876 def flexmock_remember(mocking_object)flexmock_remember165,6148 class MockContainerHelperMockContainerHelper181,6798 def next_idnext_id185,6907 def parse_should_args(mock, args, &block) # :nodoc:parse_should_args198,7380 def add_model_methods(mock, model_class, id)add_model_methods216,7893 def make_partial_proxy(container, obj, name, safe_mode)make_partial_proxy245,9111 def build_demeter_chain(mock, arg, &block)build_demeter_chain291,11097 def check_proper_mock(mock, method_name)check_proper_mock316,11944 def check_method_names(names)check_method_names326,12348 lib/flexmock/noop.rb,0 lib/flexmock/ordering.rb,399 class FlexMockFlexMock12,293 module OrderingOrdering20,665 def flexmock_allocate_orderflexmock_allocate_order23,732 def flexmock_groupsflexmock_groups29,895 def flexmock_current_orderflexmock_current_order34,1003 def flexmock_current_order=(value)flexmock_current_order=39,1126 def flexmock_validate_order(method_name, order_number)flexmock_validate_order43,1212 lib/flexmock/partial_mock.rb,1375 class FlexMockFlexMock14,318 class PartialMockProxyPartialMockProxy26,948 def initialize(obj, mock, safe_mode)initialize40,1285 def flexmock_getflexmock_get56,1685 def should_receive(*args)should_receive80,2625 def add_mock_method(method_name)add_mock_method91,2903 def new_instances(*allocators, &block)new_instances123,4119 def invoke_original(method, args)invoke_original144,4920 def flexmock_verifyflexmock_verify152,5214 def flexmock_teardownflexmock_teardown157,5350 def flexmock_containerflexmock_container169,5688 def flexmock_container=(container)flexmock_container=175,5883 def flexmock_expectations_for(method_name)flexmock_expectations_for179,5999 def sclasssclass186,6160 def singleton?(method_name)singleton?192,6301 def hide_existing_method(method_name)hide_existing_method202,6763 def stow_existing_definition(method_name)stow_existing_definition209,6980 def create_alias_for_existing_method(method_name)create_alias_for_existing_method229,7697 def define_proxy_method(method_name)define_proxy_method247,8216 def restore_original_definition(method_name)restore_original_definition268,8964 def remove_current_method(method_name)remove_current_method280,9328 def detached?detached?285,9489 def new_name(old_name)new_name290,9597 lib/flexmock/rails/view_mocking.rb,665 class FlexMockFlexMock3,20 module MockContainerMockContainer4,35 def rails_versionrails_version6,59 def should_render_view(template_name=nil)should_render_view25,684 def should_render_view_prior_version_124(template_name) # :nodoc:should_render_view_prior_version_12443,1310 def should_render_view_after_version_124(template_name)should_render_view_after_version_12464,2093 def should_render_view_after_version_202(template_name)should_render_view_after_version_20288,3015 def should_render_view_22x(template_name)should_render_view_22x109,3813 def should_render_view_23x(template_name)should_render_view_23x129,4575 lib/flexmock/rails.rb,0 lib/flexmock/recorder.rb,271 class FlexMockFlexMock14,328 class RecorderRecorder20,504 def initialize(mock)initialize24,610 def should_be_strict(is_strict=true)should_be_strict48,1542 def strict?strict?53,1656 def method_missing(sym, *args, &block)method_missing59,1786 lib/flexmock/rspec.rb,341 class FlexMockFlexMock14,319 class RSpecFrameworkAdapterRSpecFrameworkAdapter21,416 def assert_block(msg, &block)assert_block22,446 def assert_equal(a, b, msg=nil)assert_equal26,548 class AssertionFailedError < StandardError; endAssertionFailedError31,711 def assertion_failed_errorassertion_failed_error32,763 lib/flexmock/test_unit.rb,120 module TestTest14,335 module UnitUnit15,347 class TestCaseTestCase16,361 def teardownteardown25,676 lib/flexmock/test_unit_integration.rb,227 class FlexMockFlexMock15,338 module TestCaseTestCase29,895 def teardownteardown35,1070 class TestUnitFrameworkAdapterTestUnitFrameworkAdapter45,1277 def assertion_failed_errorassertion_failed_error47,1345 lib/flexmock/undefined.rb,288 class FlexMockFlexMock12,293 class UndefinedUndefined17,464 def method_missing(sym, *args, &block)method_missing18,482 def to_sto_s22,545 def inspectinspect26,587 def cloneclone30,623 def coerce(other)coerce34,657 def self.undefinedundefined43,862 lib/flexmock/validators.rb,545 class FlexMockFlexMock14,318 class CountValidatorCountValidator19,454 def initialize(expectation, limit)initialize20,477 def eligible?(n)eligible?28,733 class ExactCountValidator < CountValidatorExactCountValidator36,898 def validate(n)validate39,1022 class AtLeastCountValidator < CountValidatorAtLeastCountValidator48,1313 def validate(n)validate51,1439 def eligible?(n)eligible?61,1856 class AtMostCountValidator < CountValidatorAtMostCountValidator69,2039 def validate(n)validate71,2154 lib/flexmock.rb,0 test/redirect_error.rb,114 class FlexMockFlexMock3,20 module RedirectErrorRedirectError4,35 def redirect_errorredirect_error5,58 test/rspec_integration/integration_spec.rb,0 test/test_aliasing.rb,521 class FlexMockFlexMock5,48 module StubsAndExpectsStubsAndExpects6,63 def expects(*args)expects7,88 def stubs(*args)stubs12,234 module MockContainerMockContainer17,298 class PartialMockProxyPartialMockProxy24,407 class AliasingTest < Test::Unit::TestCaseAliasingTest30,510 def test_mockingtest_mocking33,582 def test_once_mockingtest_once_mocking39,741 def test_twice_mockingtest_twice_mocking43,837 def test_stubbingtest_stubbing48,1004 def test_partialtest_partial53,1127 test/test_container_methods.rb,1111 class TestFlexmockContainerMethods < Test::Unit::TestCaseTestFlexmockContainerMethods15,378 def test_simple_mock_creationtest_simple_mock_creation18,466 def test_mock_with_nametest_mock_with_name24,605 def test_mock_with_symbol_nametest_mock_with_symbol_name31,802 def test_mock_with_hashtest_mock_with_hash38,1005 def test_mock_with_name_and_hashtest_mock_with_name_and_hash44,1148 def test_mock_with_name_hash_and_blocktest_mock_with_name_hash_and_block53,1444 def test_basic_stubtest_basic_stub61,1665 def test_basic_stub_with_nametest_basic_stub_with_name68,1825 def test_stub_with_quick_definitionstest_stub_with_quick_definitions76,2075 def test_stub_with_name_quick_definitionstest_stub_with_name_quick_definitions82,2219 def test_stubs_are_auto_verifiedtest_stubs_are_auto_verified91,2531 def test_stubbing_a_stringtest_stubbing_a_string98,2721 def test_multiple_stubs_work_with_same_partial_mock_proxytest_multiple_stubs_work_with_same_partial_mock_proxy104,2846 def test_multiple_stubs_layer_behaviortest_multiple_stubs_layer_behavior111,3016 test/test_default_framework_adapter.rb,473 class TestFlexmockDefaultFrameworkAdapter < Test::Unit::TestCaseTestFlexmockDefaultFrameworkAdapter14,320 def setupsetup15,385 def test_assert_block_raises_exceptiontest_assert_block_raises_exception19,457 def test_assert_block_doesnt_raise_exceptiontest_assert_block_doesnt_raise_exception25,649 def test_assert_equal_doesnt_raise_exceptiontest_assert_equal_doesnt_raise_exception29,757 def test_assert_equal_can_failtest_assert_equal_can_fail33,861 test/test_demeter_mocking.rb,1568 class TestDemeterMocking < Test::Unit::TestCaseTestDemeterMocking5,48 def test_demeter_mockingtest_demeter_mocking8,126 def test_demeter_mocking_with_operatorstest_demeter_mocking_with_operators16,353 def test_demeter_mocking_with_multiple_operatorstest_demeter_mocking_with_multiple_operators25,642 def test_multiple_demeter_mocks_on_same_branch_is_oktest_multiple_demeter_mocks_on_same_branch_is_ok31,803 def test_multi_level_deep_demeter_violationtest_multi_level_deep_demeter_violation39,1095 def test_final_method_can_have_multiple_expecationstest_final_method_can_have_multiple_expecations45,1280 def test_conflicting_mock_declarations_raises_an_errortest_conflicting_mock_declarations_raises_an_error53,1571 def test_conflicting_mock_declarations_in_reverse_order_does_not_raise_errortest_conflicting_mock_declarations_in_reverse_order_does_not_raise_error65,1976 def test_preestablishing_existing_mock_is_oktest_preestablishing_existing_mock_is_ok75,2320 def test_quick_defs_can_use_demeter_mockingtest_quick_defs_can_use_demeter_mocking83,2583 def test_quick_defs_can_use_demeter_mocking_twotest_quick_defs_can_use_demeter_mocking_two93,2892 def test_errors_on_ill_formed_method_namestest_errors_on_ill_formed_method_names100,3121 def test_no_errors_on_well_formed_method_namestest_no_errors_on_well_formed_method_names109,3375 def test_readme_example_1test_readme_example_1118,3593 def test_readme_example_2test_readme_example_2128,3967 def test_readme_example_3test_readme_example_3134,4168 test/test_deprecated_methods.rb,2237 class TestFlexMock < Test::Unit::TestCaseTestFlexMock15,358 def s(&block)s19,464 def setupsetup23,514 def test_handletest_handle27,562 def test_handle_no_blocktest_handle_no_block34,706 def test_called_with_blocktest_called_with_block40,836 def test_return_valuetest_return_value47,1034 def test_handle_missing_methodtest_handle_missing_method52,1139 def test_ignore_missing_methodtest_ignore_missing_method60,1369 def test_good_countstest_good_counts66,1500 def test_bad_countstest_bad_counts74,1639 def test_undetermined_countstest_undetermined_counts85,1846 def test_zero_countstest_zero_counts94,1991 def test_file_io_with_usetest_file_io_with_use103,2160 def count_lines(stream)count_lines111,2364 def test_usetest_use119,2478 def test_failures_during_usetest_failures_during_use128,2625 def test_sequential_valuestest_sequential_values138,2844 def test_respond_to_returns_false_for_non_handled_methodstest_respond_to_returns_false_for_non_handled_methods147,3076 def test_respond_to_returns_true_for_explicit_methodstest_respond_to_returns_true_for_explicit_methods151,3211 def test_respond_to_returns_true_for_missing_methods_when_ignoring_missingtest_respond_to_returns_true_for_missing_methods_when_ignoring_missing156,3370 def test_respond_to_returns_true_for_missing_methods_when_ignoring_missing_using_shouldtest_respond_to_returns_true_for_missing_methods_when_ignoring_missing_using_should161,3551 def test_method_proc_raises_error_on_unknowntest_method_proc_raises_error_on_unknown166,3747 def test_method_returns_callable_proctest_method_returns_callable_proc172,3865 def test_method_returns_do_nothing_proc_for_missing_methodstest_method_returns_do_nothing_proc_for_missing_methods181,4121 class TestDeprecatedOrderingMethods < Test::Unit::TestCaseTestDeprecatedOrderingMethods189,4348 def test_deprecated_ordering_methodstest_deprecated_ordering_methods193,4471 class TestAnyInstance < Test::Unit::TestCaseTestAnyInstance205,4867 class DogDog209,4976 def barkbark210,4988 def test_any_instance_still_works_for_backwards_compatibilitytest_any_instance_still_works_for_backwards_compatibility215,5028 test/test_examples_from_readme.rb,1206 class TemperatureSamplerTemperatureSampler14,320 def initialize(sensor)initialize15,345 def average_tempaverage_temp19,398 class TestTemperatureSampler < Test::Unit::TestCaseTestTemperatureSampler25,525 def test_tempurature_samplertest_tempurature_sampler28,607 class TestExamplesFromReadme < Test::Unit::TestCaseTestExamplesFromReadme37,886 def test_simple_return_valuestest_simple_return_values40,968 def test_returning_an_undefined_valuetest_returning_an_undefined_value46,1108 def test_dbtest_db52,1246 def test_query_and_updatetest_query_and_update61,1476 def test_ordered_queriestest_ordered_queries70,1729 def test_ordered_queries_in_record_modetest_ordered_queries_in_record_mode88,2326 def test_build_xmltest_build_xml105,2858 def known_good_way_to_build_xml(rec)known_good_way_to_build_xml114,3113 def new_way_to_build_xml(rec)new_way_to_build_xml119,3183 def test_multiple_getstest_multiple_gets123,3271 def test_an_important_messagetest_an_important_message132,3516 class QuoteServiceQuoteService141,3746 class PortfolioPortfolio143,3773 def valuevalue144,3791 def test_portfolio_valuetest_portfolio_value149,3849 test/test_extended_should_receive.rb,808 module ExtendedShouldReceiveTestsExtendedShouldReceiveTests14,320 def test_accepts_expectation_hashtest_accepts_expectation_hash15,354 def test_accepts_list_of_methodstest_accepts_list_of_methods21,518 def test_contraints_apply_to_all_expectationstest_contraints_apply_to_all_expectations28,676 def test_count_contraints_apply_to_all_expectationstest_count_contraints_apply_to_all_expectations35,943 def test_multiple_should_receives_are_allowedtest_multiple_should_receives_are_allowed41,1134 class TestExtendedShouldReceiveOnFullMocks < Test::Unit::TestCaseTestExtendedShouldReceiveOnFullMocks49,1351 def setupsetup53,1484 class TestExtendedShouldReceiveOnPartialMockProxies < Test::Unit::TestCaseTestExtendedShouldReceiveOnPartialMockProxies60,1554 def setupsetup64,1696 test/test_flexmodel.rb,528 class DummyModelDummyModel5,48 class ChildModel < DummyModelChildModel8,70 class TestFlexModel < Test::Unit::TestCaseTestFlexModel12,176 def test_initial_conditionstest_initial_conditions15,249 def test_classifying_mock_modelstest_classifying_mock_models27,650 def test_mock_models_have_different_idstest_mock_models_have_different_ids37,897 def test_mock_models_can_have_quick_defstest_mock_models_can_have_quick_defs43,1048 def test_mock_models_can_have_blockstest_mock_models_can_have_blocks48,1188 test/test_naming.rb,816 class TestNaming < Test::Unit::TestCaseTestNaming14,320 def test_nametest_name17,390 def test_name_in_no_handler_found_errortest_name_in_no_handler_found_error22,473 def test_name_in_received_count_errortest_name_in_received_count_error31,689 def test_naming_with_usetest_naming_with_use40,909 def test_naming_with_multiple_mocks_in_usetest_naming_with_multiple_mocks_in_use46,1026 def test_inspect_returns_reasonable_nametest_inspect_returns_reasonable_name53,1214 def test_mock_can_override_inspecttest_mock_can_override_inspect60,1398 class DummyDummy67,1601 def inspectinspect68,1615 def test_partial_mocks_use_original_inspecttest_partial_mocks_use_original_inspect73,1668 def test_partial_mocks_can_override_inspecttest_partial_mocks_can_override_inspect79,1832 test/test_new_instances.rb,2271 class TestNewInstances < Test::Unit::TestCaseTestNewInstances14,320 class DogDog18,430 def barkbark19,442 def wagwag22,475 def self.makemake25,507 class CatCat30,550 def initialize(name, &block)initialize32,584 class ConnectionConnection38,690 def initialize(*args)initialize39,709 def send(args)send42,777 def post(args)post45,821 def test_new_instances_allows_stubbing_of_existing_methodstest_new_instances_allows_stubbing_of_existing_methods50,872 def test_new_instances_stubs_still_have_existing_methodstest_new_instances_stubs_still_have_existing_methods58,1093 def test_new_instances_will_pass_args_to_newtest_new_instances_will_pass_args_to_new66,1308 def test_new_gets_block_after_restubbingtest_new_gets_block_after_restubbing79,1714 def test_new_instances_stub_verification_happens_on_teardowntest_new_instances_stub_verification_happens_on_teardown92,2035 def test_new_instances_reports_error_on_non_classestest_new_instances_reports_error_on_non_classes102,2380 def test_does_not_by_default_stub_objects_created_with_allocatetest_does_not_by_default_stub_objects_created_with_allocate112,2659 def test_can_explicitly_stub_objects_created_with_allocatetest_can_explicitly_stub_objects_created_with_allocate120,2887 def test_can_stub_objects_created_with_arbitrary_class_methodstest_can_stub_objects_created_with_arbitrary_class_methods128,3124 def test_stubbing_arbitrary_class_methods_leaves_new_alonetest_stubbing_arbitrary_class_methods_leaves_new_alone135,3347 def test_stubbing_new_and_allocate_doesnt_double_stub_objects_on_newtest_stubbing_new_and_allocate_doesnt_double_stub_objects_on_new142,3562 def test_blocks_on_new_do_not_have_stubs_installedtest_blocks_on_new_do_not_have_stubs_installed155,4015 def test_new_instances_accept_chained_expectationstest_new_instances_accept_chained_expectations169,4353 def test_fancy_use_of_chained_should_receivedtest_fancy_use_of_chained_should_received177,4623 def test_writable_accessorstest_writable_accessors182,4778 def test_ordering_can_be_specifiedtest_ordering_can_be_specified188,4923 def test_ordering_can_be_specified_in_groupstest_ordering_can_be_specified_in_groups196,5117 test/test_partial_mock.rb,4962 class TestStubbing < Test::Unit::TestCaseTestStubbing14,320 class DogDog17,392 def barkbark18,404 def Dog.createcreate21,437 class DogPlus < DogDogPlus26,486 def should_receiveshould_receive27,508 def new_instancesnew_instances30,557 def by_defaultby_default33,602 def test_stub_command_add_behavior_to_arbitrary_objectstest_stub_command_add_behavior_to_arbitrary_objects38,658 def test_stub_command_can_configure_via_blocktest_stub_command_can_configure_via_block44,842 def test_stubbed_methods_can_take_blockstest_stubbed_methods_can_take_blocks52,1039 def test_multiple_stubs_on_the_same_object_reuse_the_same_partial_mocktest_multiple_stubs_on_the_same_object_reuse_the_same_partial_mock59,1264 def test_multiple_methods_can_be_stubbedtest_multiple_methods_can_be_stubbed64,1411 def test_original_behavior_can_be_restoredtest_original_behavior_can_be_restored72,1663 def test_original_missing_behavior_can_be_restoredtest_original_missing_behavior_can_be_restored82,1998 def test_multiple_stubs_on_single_method_can_be_restored_missing_methodtest_multiple_stubs_on_single_method_can_be_restored_missing_method91,2277 def test_original_behavior_is_restored_when_multiple_methods_are_mockedtest_original_behavior_is_restored_when_multiple_methods_are_mocked102,2686 def test_original_behavior_is_restored_on_class_objectstest_original_behavior_is_restored_on_class_objects111,3015 def test_original_behavior_is_restored_on_singleton_methodstest_original_behavior_is_restored_on_singleton_methods118,3262 def obj.hi() :hello endhi120,3345 def test_original_behavior_is_restored_on_singleton_methods_with_multiple_stubstest_original_behavior_is_restored_on_singleton_methods_with_multiple_stubs128,3541 def obj.hi(n) "hello#{n}" endhi130,3644 def test_original_behavior_is_restored_on_nonsingleton_methods_with_multiple_stubstest_original_behavior_is_restored_on_nonsingleton_methods_with_multiple_stubs140,3965 def test_stubbing_file_shouldnt_break_writingtest_stubbing_file_shouldnt_break_writing156,4459 def test_original_behavior_is_restored_even_when_errorstest_original_behavior_is_restored_even_when_errors172,4898 def m.flexmock_verify() endflexmock_verify180,5217 def test_not_calling_stubbed_method_is_an_errortest_not_calling_stubbed_method_is_an_error183,5256 def test_mock_is_verified_when_the_stub_is_verifiedtest_mock_is_verified_when_the_stub_is_verified192,5474 def test_stub_can_have_explicit_nametest_stub_can_have_explicit_name201,5731 def test_unamed_stub_will_use_default_naming_conventiontest_unamed_stub_will_use_default_naming_convention207,5910 def test_partials_can_be_defined_in_a_blocktest_partials_can_be_defined_in_a_block213,6106 def test_partials_defining_block_return_real_obj_not_proxytest_partials_defining_block_return_real_obj_not_proxy221,6293 def test_partial_mocks_always_return_domain_objecttest_partial_mocks_always_return_domain_object228,6487 def test_domain_objects_do_not_have_mock_methodstest_domain_objects_do_not_have_mock_methods239,6767 def test_partial_mocks_have_mock_methodstest_partial_mocks_have_mock_methods246,6959 def test_partial_mocks_do_not_have_mock_methods_after_teardowntest_partial_mocks_do_not_have_mock_methods_after_teardown254,7155 def test_partial_mocks_with_mock_method_singleton_colision_have_original_defs_restoredtest_partial_mocks_with_mock_method_singleton_colision_have_original_defs_restored263,7405 def dog.mock() :original endmock265,7512 class MockColisionMockColision271,7633 def mockmock272,7654 def test_partial_mocks_with_mock_method_non_singleton_colision_have_original_defs_restoredtest_partial_mocks_with_mock_method_non_singleton_colision_have_original_defs_restored277,7698 def test_safe_partial_mocks_do_not_support_mock_methodstest_safe_partial_mocks_do_not_support_mock_methods284,7902 def test_safe_partial_mocks_require_blocktest_safe_partial_mocks_require_block292,8130 def test_safe_partial_mocks_are_actually_mockedtest_safe_partial_mocks_are_actually_mocked297,8268 def test_should_receive_does_not_override_preexisting_deftest_should_receive_does_not_override_preexisting_def302,8438 def test_should_receive_does_override_should_receive_preexisting_deftest_should_receive_does_override_should_receive_preexisting_def308,8638 class LiarLiar313,8822 def respond_to?(method_name)respond_to?314,8835 def test_liar_actually_liestest_liar_actually_lies324,9004 def test_partial_mock_where_respond_to_is_true_yet_method_is_not_theretest_partial_mock_where_respond_to_is_true_yet_method_is_not_there330,9156 class ValueObjectValueObject341,9585 def initialize(val)initialize344,9627 def ==(other)==348,9677 def test_partial_mocks_in_the_presense_of_equal_definitiontest_partial_mocks_in_the_presense_of_equal_definition353,9734 test/test_rails_view_stub.rb,1492 module ViewTestsViewTests6,86 def test_view_mocks_as_stubtest_view_mocks_as_stub7,103 def test_fails_if_no_rendertest_fails_if_no_render12,197 def test_view_mocks_with_expectationtest_view_mocks_with_expectation19,331 def test_view_mocks_with_expectation_fails_with_different_templatetest_view_mocks_with_expectation_fails_with_different_template24,435 def test_view_mocks_with_expectation_and_multiple_templatestest_view_mocks_with_expectation_and_multiple_templates32,644 def pretend_to_be_rails_version(version)pretend_to_be_rails_version39,820 class TestRailsViewStubForVersionsUpTo_1_2_4 < Test::Unit::TestCaseTestRailsViewStubForVersionsUpTo_1_2_445,1015 def setupsetup49,1133 def render(*names)render56,1362 class TestRailsViewStubForVersionsAfter_1_2_4 < Test::Unit::TestCaseTestRailsViewStubForVersionsAfter_1_2_470,1640 def setupsetup74,1759 def render(*names)render82,2032 class TestRailsViewStubForVersionsAfter_2_0_2 < Test::Unit::TestCaseTestRailsViewStubForVersionsAfter_2_0_297,2334 def setupsetup101,2453 def render(*names)render109,2728 class FlexMockFlexMock123,2983 module MockContainerMockContainer124,2998 module RailsRails125,3021 module VERSIONVERSION126,3038 class TestRailsVersion < Test::Unit::TestCaseTestRailsVersion133,3107 def test_rails_version_to_get_code_coveragetest_rails_version_to_get_code_coverage135,3182 module ActionViewActionView142,3280 class BaseBase143,3298 test/test_record_mode.rb,1339 class TestRecordMode < Test::Unit::TestCaseTestRecordMode14,320 def test_recording_mode_workstest_recording_mode_works17,394 def test_arguments_are_passed_to_recording_mode_blocktest_arguments_are_passed_to_recording_mode_block25,568 def test_recording_mode_handles_multiple_returnstest_recording_mode_handles_multiple_returns36,832 def test_recording_mode_does_not_specify_ordertest_recording_mode_does_not_specify_order50,1242 def test_recording_mode_gets_block_args_tootest_recording_mode_gets_block_args_too61,1477 def test_recording_mode_should_validate_args_with_equalstest_recording_mode_should_validate_args_with_equals73,1747 def test_recording_mode_should_allow_arg_contraint_validationtest_recording_mode_should_allow_arg_contraint_validation84,1971 def test_recording_mode_should_handle_multiplicity_contraintstest_recording_mode_should_handle_multiplicity_contraints95,2200 def test_strict_record_mode_requires_exact_argument_matchestest_strict_record_mode_requires_exact_argument_matches107,2455 def test_strict_record_mode_requires_exact_orderingtest_strict_record_mode_requires_exact_ordering119,2723 def test_strict_record_mode_requires_oncetest_strict_record_mode_requires_once133,3014 def test_strict_record_mode_can_not_failtest_strict_record_mode_can_not_fail146,3276 test/test_samples.rb,2164 class TestSamples < Test::Unit::TestCaseTestSamples16,346 def test_file_iotest_file_io24,716 def count_lines(file)count_lines32,967 class TestUndefined < Test::Unit::TestCaseTestUndefined42,1060 def test_undefined_valuestest_undefined_values45,1133 class TestSimple < Test::Unit::TestCaseTestSimple54,1319 def test_simple_mocktest_simple_mock57,1389 class TestDog < Test::Unit::TestCaseTestDog64,1524 def test_dog_wagstest_dog_wags67,1591 class WooferWoofer73,1702 class DogDog76,1720 def initializeinitialize77,1730 def barkbark80,1778 def wagwag83,1812 class TestDogBarking < Test::Unit::TestCaseTestDogBarking88,1844 def setupsetup93,2006 def test_dogtest_dog98,2079 class TestDogBarkingWithNewInstances < Test::Unit::TestCaseTestDogBarkingWithNewInstances104,2210 def setupsetup109,2374 def test_dogtest_dog113,2459 class TestDefaults < Test::Unit::TestCaseTestDefaults119,2593 def setupsetup122,2665 def test_something_where_bark_must_be_called_oncetest_something_where_bark_must_be_called_once127,2792 class TestDemeter < Test::Unit::TestCaseTestDemeter135,2994 def test_manual_mockingtest_manual_mocking137,3064 def test_demetertest_demeter150,3498 class TestDb < Test::Unit::TestCaseTestDb160,3713 def test_dbtest_db163,3779 class TestDb < Test::Unit::TestCaseTestDb174,3984 def test_query_and_updatetest_query_and_update177,4050 def test_ordered_queriestest_ordered_queries188,4327 def test_ordered_queries_in_record_modetest_ordered_queries_in_record_mode206,4867 def known_good_way_to_build_xml(builder)known_good_way_to_build_xml223,5342 def new_way_to_build_xml(builder)new_way_to_build_xml227,5409 def test_build_xmltest_build_xml231,5493 class TestMoreSamples < Test::Unit::TestCaseTestMoreSamples242,5753 def test_multiple_getstest_multiple_gets245,5828 def test_an_important_messagetest_an_important_message254,6073 class QuoteServiceQuoteService263,6334 class PortfolioPortfolio266,6362 def initializeinitialize267,6380 def valuevalue270,6447 def test_portfolio_valuetest_portfolio_value275,6503 test/test_setup.rb,180 class FlexMockFlexMock7,91 module TestCaseTestCase8,106 def assertion_failed_errorassertion_failed_error9,124 def assert_failure(message=nil)assert_failure16,378 test/test_should_ignore_missing.rb,1173 class TestShouldIgnoreMissing < Test::Unit::TestCaseTestShouldIgnoreMissing14,320 def setupsetup17,403 def test_mocks_do_not_respond_to_undefined_methodstest_mocks_do_not_respond_to_undefined_methods21,451 def test_mocks_do_respond_to_defined_methodstest_mocks_do_respond_to_defined_methods25,555 def test_mocks_do_respond_to_any_method_when_ignoring_missingtest_mocks_do_respond_to_any_method_when_ignoring_missing30,695 def test_ignored_methods_return_undefinedtest_ignored_methods_return_undefined35,841 def test_undefined_mocking_with_argumentstest_undefined_mocking_with_arguments41,1015 def test_method_chains_with_undefined_are_self_preservingtest_method_chains_with_undefined_are_self_preserving46,1163 def test_method_proc_raises_error_on_unknowntest_method_proc_raises_error_on_unknown51,1328 def test_method_returns_callable_proctest_method_returns_callable_proc57,1452 def test_not_calling_method_proc_will_fail_count_constraintstest_not_calling_method_proc_will_fail_count_constraints64,1636 def test_method_returns_do_nothing_proc_for_missing_methodstest_method_returns_do_nothing_proc_for_missing_methods73,1898 test/test_should_receive.rb,11020 def mock_top_level_functionmock_top_level_function14,320 module KernelKernel18,361 def mock_kernel_functionmock_kernel_function19,375 class CatCat25,441 def purrpurr26,451 def meowmeow28,468 class TestFlexMockShoulds < Test::Unit::TestCaseTestFlexMockShoulds32,490 def test_defaultstest_defaults43,995 def test_returns_with_valuetest_returns_with_value52,1163 def test_returns_with_multiple_valuestest_returns_with_multiple_values60,1330 def test_multiple_returnstest_multiple_returns71,1590 def test_returns_with_blocktest_returns_with_block82,1850 def test_block_example_from_readmetest_block_example_from_readme91,2053 def test_return_with_and_without_block_interleavedtest_return_with_and_without_block_interleaved101,2349 def test_and_returns_aliastest_and_returns_alias111,2629 def test_and_return_undefinedtest_and_return_undefined118,2766 def test_and_yield_will_continue_to_yield_the_same_valuetest_and_yield_will_continue_to_yield_the_same_value128,3115 def test_and_yield_with_multiple_values_yields_the_valuestest_and_yield_with_multiple_values_yields_the_values136,3361 def test_multiple_yields_are_done_sequentiallytest_multiple_yields_are_done_sequentially143,3571 def test_failure_if_no_block_giventest_failure_if_no_block_given152,3843 def test_failure_different_return_value_than_yield_returntest_failure_different_return_value_than_yield_return159,4026 def test_multiple_yieldstest_multiple_yields168,4312 def test_multiple_yields_will_yield_the_last_value_settest_multiple_yields_will_yield_the_last_value_set176,4550 def test_yielding_then_not_yielding_and_then_yielding_againtest_yielding_then_not_yielding_and_then_yielding_again187,4927 def test_yields_syntaxtest_yields_syntax198,5274 class MyError < RuntimeErrorMyError205,5419 def test_and_raises_with_exception_class_throws_exceptiontest_and_raises_with_exception_class_throws_exception208,5457 def test_and_raises_with_arguments_throws_exception_made_with_argstest_and_raises_with_arguments_throws_exception_made_with_args217,5666 def test_and_raises_with_a_specific_exception_throws_the_exceptiontest_and_raises_with_a_specific_exception_throws_the_exception227,5947 def test_raises_is_an_alias_for_and_raisetest_raises_is_an_alias_for_and_raise238,6217 def test_multiple_and_raise_clauses_will_be_done_sequentiallytest_multiple_and_raise_clauses_will_be_done_sequentially247,6422 def test_and_throw_will_throw_a_symboltest_and_throw_will_throw_a_symbol259,6820 def test_and_throw_with_expression_will_throwtest_and_throw_with_expression_will_throw270,7063 def test_throws_is_an_alias_for_and_throwtest_throws_is_an_alias_for_and_throw281,7345 def test_multiple_throws_will_be_done_sequentiallytest_multiple_throws_will_be_done_sequentially292,7620 def test_multiple_expectationstest_multiple_expectations304,7950 def test_with_no_args_with_no_argstest_with_no_args_with_no_args314,8181 def test_with_no_args_but_with_argstest_with_no_args_but_with_args321,8309 def test_with_any_argstest_with_any_args330,8508 def test_with_any_single_arg_matchingtest_with_any_single_arg_matching340,8686 def test_with_any_single_arg_nonmatchingtest_with_any_single_arg_nonmatching348,8879 def test_with_equal_arg_matchingtest_with_equal_arg_matching358,9114 def test_with_ducktype_arg_matchingtest_with_ducktype_arg_matching365,9277 def test_with_ducktype_arg_matching_no_matchtest_with_ducktype_arg_matching_no_match372,9456 def test_with_hash_matchingtest_with_hash_matching381,9680 def test_with_hash_non_matchingtest_with_hash_non_matching388,9868 def test_with_equal_arg_nonmatchingtest_with_equal_arg_nonmatching397,10088 def test_with_arbitrary_arg_matchingtest_with_arbitrary_arg_matching406,10325 def test_args_matching_with_regextest_args_matching_with_regex421,10745 def test_arg_matching_with_regex_matching_non_stringtest_arg_matching_with_regex_matching_non_string433,11066 def test_arg_matching_with_classtest_arg_matching_with_class440,11243 def test_arg_matching_with_no_matchtest_arg_matching_with_no_match451,11527 def test_arg_matching_with_string_doesnt_over_matchtest_arg_matching_with_string_doesnt_over_match460,11740 def test_block_arg_given_to_no_argstest_block_arg_given_to_no_args469,11959 def test_block_arg_given_to_matching_proctest_block_arg_given_to_matching_proc478,12163 def test_arg_matching_precedence_when_best_firsttest_arg_matching_precedence_when_best_first489,12448 def test_arg_matching_precedence_when_best_last_but_still_matches_firsttest_arg_matching_precedence_when_best_last_but_still_matches_first497,12657 def test_never_and_never_calledtest_never_and_never_called505,12889 def test_never_and_called_oncetest_never_and_called_once511,13004 def test_once_called_oncetest_once_called_once520,13196 def test_once_but_never_calledtest_once_but_never_called527,13330 def test_once_but_called_twicetest_once_but_called_twice535,13517 def test_twice_and_called_twicetest_twice_and_called_twice545,13736 def test_zero_or_more_called_zerotest_zero_or_more_called_zero553,13891 def test_zero_or_more_called_oncetest_zero_or_more_called_once559,14013 def test_zero_or_more_called_100test_zero_or_more_called_100566,14146 def test_timestest_times573,14292 def test_at_least_called_oncetest_at_least_called_once580,14433 def test_at_least_but_never_calledtest_at_least_but_never_called587,14580 def test_at_least_once_but_called_twicetest_at_least_once_but_called_twice595,14783 def test_at_least_and_exacttest_at_least_and_exact603,14954 def test_at_most_but_never_calledtest_at_most_but_never_called613,15184 def test_at_most_called_oncetest_at_most_called_once619,15320 def test_at_most_called_twicetest_at_most_called_twice626,15465 def test_at_most_and_at_least_called_nevertest_at_most_and_at_least_called_never636,15693 def test_at_most_and_at_least_called_oncetest_at_most_and_at_least_called_once644,15918 def test_at_most_and_at_least_called_twicetest_at_most_and_at_least_called_twice651,16091 def test_at_most_and_at_least_called_three_timestest_at_most_and_at_least_called_three_times659,16279 def test_call_counts_only_apply_to_matching_argstest_call_counts_only_apply_to_matching_args670,16557 def test_call_counts_only_apply_to_matching_args_with_mismatchtest_call_counts_only_apply_to_matching_args_with_mismatch682,16835 def test_ordered_calls_in_order_will_passtest_ordered_calls_in_order_will_pass698,17268 def test_ordered_calls_out_of_order_will_failtest_ordered_calls_out_of_order_will_fail708,17450 def test_order_calls_with_different_arg_lists_and_in_order_will_passtest_order_calls_with_different_arg_lists_and_in_order_will_pass720,17711 def test_order_calls_with_different_arg_lists_and_out_of_order_will_failtest_order_calls_with_different_arg_lists_and_out_of_order_will_fail730,17958 def test_unordered_calls_do_not_effect_ordered_testingtest_unordered_calls_do_not_effect_ordered_testing742,18284 def test_ordered_with_multiple_calls_will_passtest_ordered_with_multiple_calls_will_pass756,18548 def test_grouped_ordering_with_numberstest_grouped_ordering_with_numbers768,18757 def test_grouped_ordering_with_symbolstest_grouped_ordering_with_symbols783,19072 def test_explicit_ordering_mixed_with_implicit_ordering_should_not_overlaptest_explicit_ordering_mixed_with_implicit_ordering_should_not_overlap798,19428 def test_explicit_ordering_with_explicit_misorderstest_explicit_ordering_with_explicit_misorders808,19801 def test_ordering_with_explicit_no_args_matches_correctlytest_ordering_with_explicit_no_args_matches_correctly824,20329 def test_ordering_with_any_arg_matching_correctly_matchestest_ordering_with_any_arg_matching_correctly_matches836,20702 def test_ordering_between_mocks_is_not_normally_definedtest_ordering_between_mocks_is_not_normally_defined847,21010 def test_ordering_between_mocks_is_honored_for_global_orderingtest_ordering_between_mocks_is_honored_for_global_ordering859,21264 def test_expectation_formatingtest_expectation_formating871,21573 def test_multi_expectation_formattingtest_multi_expectation_formatting880,21801 def test_explicit_ordering_with_limits_allow_multiple_return_valuestest_explicit_ordering_with_limits_allow_multiple_return_values886,21964 def test_global_methods_can_be_mockedtest_global_methods_can_be_mocked905,22675 def test_kernel_methods_can_be_mockedtest_kernel_methods_can_be_mocked911,22859 def test_undefing_kernel_methods_dont_effect_other_mockstest_undefing_kernel_methods_dont_effect_other_mocks917,23037 def test_expectations_can_by_marked_as_defaulttest_expectations_can_by_marked_as_default925,23305 def test_default_expectations_are_search_in_the_proper_ordertest_default_expectations_are_search_in_the_proper_order931,23467 def test_expectations_with_count_constraints_can_by_marked_as_defaulttest_expectations_with_count_constraints_can_by_marked_as_default939,23770 def test_default_expectations_are_overridden_by_later_expectationstest_default_expectations_are_overridden_by_later_expectations947,24006 def test_default_expectations_can_be_changed_by_later_expectationstest_default_expectations_can_be_changed_by_later_expectations955,24234 def test_ordered_default_expectations_can_be_specifiedtest_ordered_default_expectations_can_be_specified966,24596 def test_ordered_default_expectations_can_be_overriddentest_ordered_default_expectations_can_be_overridden974,24837 def test_by_default_works_at_mock_leveltest_by_default_works_at_mock_level986,25108 def test_by_default_at_mock_level_does_nothing_with_no_expectationstest_by_default_at_mock_level_does_nothing_with_no_expectations997,25383 def test_partial_mocks_can_have_default_expectationstest_partial_mocks_can_have_default_expectations1003,25528 def test_partial_mocks_can_have_default_expectations_overriddentest_partial_mocks_can_have_default_expectations_overridden1009,25709 def test_wicked_and_evil_tricks_with_by_default_are_thwartedtest_wicked_and_evil_tricks_with_by_default_are_thwarted1016,25957 def test_mocks_can_handle_multi_parameter_respond_tostest_mocks_can_handle_multi_parameter_respond_tos1028,26362 def test_can_mock_operatorstest_can_mock_operators1039,26709 def assert_operator(op, &block)assert_operator1069,27773 class TestFlexMockShouldsWithInclude < Test::Unit::TestCaseTestFlexMockShouldsWithInclude1077,27927 def test_include_enables_unqualified_arg_type_referencestest_include_enables_unqualified_arg_type_references1079,28021 class TestFlexMockArgTypesDontLeak < Test::Unit::TestCaseTestFlexMockArgTypesDontLeak1087,28185 def test_unqualified_arg_type_references_are_undefined_by_defaulttest_unqualified_arg_type_references_are_undefined_by_default1088,28243 test/test_tu_integration.rb,1570 class TestTuIntegrationFlexMockMethod < Test::Unit::TestCaseTestTuIntegrationFlexMockMethod14,320 def test_can_construct_flexmocktest_can_construct_flexmock17,411 def test_can_construct_flexmock_with_blocktest_can_construct_flexmock_with_block23,558 class TestTuIntegrationMockVerificationInTeardown < Test::Unit::TestCaseTestTuIntegrationMockVerificationInTeardown31,734 def teardownteardown34,837 def test_mock_verification_occurs_during_teardowntest_mock_verification_occurs_during_teardown40,923 class TestTuIntegrationMockVerificationWithoutSetup < Test::Unit::TestCaseTestTuIntegrationMockVerificationWithoutSetup45,1041 def teardownteardown48,1146 def test_mock_verification_occurs_during_teardowntest_mock_verification_occurs_during_teardown54,1232 class TestTuIntegrationMockVerificationForgetfulSetup < Test::Unit::TestCaseTestTuIntegrationMockVerificationForgetfulSetup59,1350 def teardownteardown62,1457 def test_mock_verification_occurs_during_teardowntest_mock_verification_occurs_during_teardown68,1543 class TestTuIntegrationSetupOverridenAndNoMocksOk < Test::Unit::TestCaseTestTuIntegrationSetupOverridenAndNoMocksOk73,1661 def test_mock_verification_occurs_during_teardowntest_mock_verification_occurs_during_teardown76,1764 class TestTuIntegrationFailurePreventsVerification < Test::Unit::TestCaseTestTuIntegrationFailurePreventsVerification80,1827 def test_mock_verification_occurs_during_teardowntest_mock_verification_occurs_during_teardown83,1931 def simulate_failuresimulate_failure90,2065 test/test_undefined.rb,873 class UndefinedTest < Test::Unit::TestCaseUndefinedTest14,320 def test_undefined_method_calls_return_undefinedtest_undefined_method_calls_return_undefined15,363 def test_equalstest_equals19,481 def test_math_operatorstest_math_operators24,579 def test_math_operators_reversedtest_math_operators_reversed32,788 def test_comparisonstest_comparisons40,1006 def test_comparisons_reversedtest_comparisons_reversed48,1215 def test_base_level_methodstest_base_level_methods56,1433 def test_cant_create_a_new_undefinedtest_cant_create_a_new_undefined60,1520 def test_cant_clone_undefinedtest_cant_clone_undefined64,1630 def test_string_representationstest_string_representations69,1764 def test_undefined_is_not_niltest_undefined_is_not_nil74,1902 def assert_undefined(obj)assert_undefined80,1980 def undefinedundefined84,2043 test/test_unit_integration/test_auto_test_unit.rb,263 class TestFlexmockTestUnit < Test::Unit::TestCaseTestFlexmockTestUnit17,374 def teardownteardown18,424 def test_can_create_mockstest_can_create_mocks23,483 def test_should_fail__mocks_are_auto_verifiedtest_should_fail__mocks_are_auto_verified30,626 flexmock-0.9.0/README.rdoc0000644000175000017500000010175711661521733015370 0ustar terceiroterceiro= Flex Mock -- Making Mock Easy FlexMock is a simple, but flexible, mock object library for Ruby unit testing. Version :: 0.9.0.beta.0 = Links Documents :: http://flexmock.rubyforge.org RubyGems :: Install with: gem install flexmock Download :: Download from RubyForge at http://rubyforge.org/frs/?group_id=3433 (pre 0.6.0 versions may be found at http://rubyforge.org/frs/?group_id=170) Issue Tracking :: http://www.pivotaltracker.com/projects/28401 Bug Reports :: http://onestepback.org/cgi-bin/bugs.cgi?project=flexmock == Installation You can install FlexMock with the following command. $ gem install flexmock == Simple Example We have a data acquisition class (+TemperatureSampler+) that reads a temperature sensor and returns an average of 3 readings. We don't have a _real_ temperature to use for testing, so we mock one up with a mock object that responds to the +read_temperature+ message. Here's the complete example: require 'test/unit' require 'flexmock/test_unit' class TemperatureSampler def initialize(sensor) @sensor = sensor end def average_temp total = (0...3).collect { @sensor.read_temperature }.inject { |i, s| i + s } total / 3.0 end end class TestTemperatureSampler < Test::Unit::TestCase def test_sensor_can_average_three_temperature_readings sensor = flexmock("temp") sensor.should_receive(:read_temperature).times(3). and_return(10, 12, 14) sampler = TemperatureSampler.new(sensor) assert_equal 12, sampler.average_temp end end You can find an extended example of FlexMock in {Google Example}[http://flexmock.rubyforge.org/files/doc/GoogleExample_rdoc.html]. == Test::Unit Integration FlexMock integrates nicely with Test::Unit. Just require the 'flexmock/test_unit' file at the top of your test file. The +flexmock+ method will be available for mock creation, and any created mocks will be automatically validated and closed at the end of the individual test. Your test case will look something like this: require 'flexmock/test_unit' class TestDog < Test::Unit::TestCase def test_dog_wags tail_mock = flexmock(:wag => :happy) assert_equal :happy, tail_mock.wag end end NOTE: If you don't want to automatically extend every TestCase with the flexmock methods and overhead, then require the 'flexmock' file and explicitly include the FlexMock::TestCase module in each test case class where you wish to use mock objects. FlexMock versions prior to 0.6.0 required the explicit include. == RSpec Integration FlexMock also supports integration with the RSpec behavior specification framework. Starting with version 0.9.0 of RSpec, you will be able to say: Spec::Runner.configure do |config| config.mock_with :flexmock end describe "Using FlexMock with RSpec" do it "should be able to create a mock" do m = flexmock(:foo => :bar) m.foo.should === :bar end end If you wish to try this prior to the release of RSpec 0.9.0, check out the trunk of the RSpec subversion repository. == Quick Reference === Creating Mock Objects The +flexmock+ method is used to create mocks in various configurations. Here's a quick rundown of the most common options. See FlexMock::MockContainer#flexmock for more details. * mock = flexmock("joe") Create a mock object named "joe" (the name is used in reporting errors). * mock = flexmock(:foo => :bar, :baz => :froz) Create a mock object and define two mocked methods (:foo and :baz) that return the values :bar and :froz respectively. This is useful when creating mock objects with just a few methods and simple return values. * mock = flexmock("joe", :foo => :bar, :bar => :froz) You can combine the mock name and an expectation hash in the same call to flexmock. * partial_mock = flexmock(real_object) If you you give +flexmock+ a real object in the argument list, it will treat that real object as a base for a partial mock object. The return value +m+ may be used to set expectations. The real_object should be used in the reference portion of the test. * partial_mock = flexmock(real_object, "name", :foo => :baz) Names and expectation hashes may be used with partial mocks as well. * partial_mock = flexmock(:base, real_string_object) Since Strings (and Symbols for that matter) are used for mock names, FlexMock will not recognize them as the base for a partial mock. To force a string to be used as a partial mock base, proceed the string object in the calling sequence with :base. * partial_mock = flexmock(:safe, real_object) { |mock| mock.should_receive(...) } When mocking real objects (i.e. "partial mocks"), FlexMock will add a handful of mock related methods to the actual object (see below for list of method names). If one or more of these added methods collide with an existing method on the partial mock, then there are problems. FlexMock offers a "safe" mode for partial mocks that does not add these methods. Indicate safe mode by passing the symbol :safe as the first argument of flexmock. A block is required when using safe mode (the partial_mock returned in safe mode does not have a +should_receive+ method). The methods added to partial mocks in non-safe mode are: * should_receive * new_instances * any_instance (note: deprecated) * mock * mock_teardown * mock_setup * mock = flexmock(...) { |mock| mock.should_receive(...) } If a block is given to any of the +flexmock+ forms, the mock object will be passed to the block as an argument. Code in the block can set the desired expectations for the mock object. * mock_model = flexmock(:model, YourModel, ...) { |mock| mock.should_receive(...) } When given :model, flexmock() will return a pure mock (not a partial mock) that will have some ActiveRecord specific methods defined. YourModel should be the class of an ActiveRecord model. These predefined methods make it a bit easier to mock out ActiveRecord model objects in a Rails application. Other that the predefined mocked methods, the mock returned is a standard FlexMock mock object. The predefined mocked methods are: * id -- returns a unique ID for each mocked model. * to_params -- returns a stringified version of the id. * new_record? -- returns false. * errors -- returns an empty (mocked) errors object. * is_a?(other) -- returns true if other == YourModel. * instance_of?(class) -- returns true if class == YourModel * kind_of?(class) -- returns true if class is YourModel or one of its ancestors * class -- returns YourModel. NOTE: Versions of FlexMock prior to 0.6.0 used +flexstub+ to create partial mocks. The +flexmock+ method now assumes all the functionality that was spread out between two different methods. +flexstub+ is still available for backward compatibility. === Expectation Declarators Once a mock is created, you need to define what that mock should expect to see. Expectation declarators are used to specify these expectations placed upon received method calls. A basic expectation, created with the +should_receive+ method, just establishes the fact that a method may (or may not) be called on the mock object. Refinements to that expectation may be additionally declared. FlexMock always starts with the most general expectation and adds constraints to that. For example, the following code: mock.should_receive(:average).and_return(12) Means that the mock will now accept method calls to an +average+ method. The expectation will accept any arguments and may be called any number of times (including zero times). Strictly speaking, the +and_return+ part of the declaration isn't exactly a constraint, but it does specify what value the mock will return when the expectation is matched. If you want to be more specific, you need to add additional constraints to your expectation. Here are some examples: mock.should_receive(:average).with(12).once mock.should_receive(:average).with(Integer). at_least.twice.at_most.times(10). and_return { rand } The following methods may be used to create and refine expectations on a mock object. See theFlexMock::Expectation for more details. * should_receive(method_name) Declares that a message named method_name will be sent to the mock object. Constraints on this expected message (called expectations) may be chained to the +should_receive+ call. * should_receive(method_name1, method_name2, ...) Define a number of expected messages that have the same constraints. * should_receive(meth1 => result1, meth2 => result2, ...) Define a number of expected messages that have the same constrants, but return different values. * should_expect { |recorder| ... } Creates a mock recording object that will translate received method calls into mock expectations. The recorder is passed to a block supplied with the +should_expect+ method. See examples below. * with(arglist) Declares that this expectation matches messages that match the given argument list. The === operator is used on a argument by argument basis to determine matching. This means that most literal values match literally, class values match any instance of a class and regular expression match any matching string (after a +to_s+ conversion). See argument validators (below) for details on argument validation options. * with_any_args Declares that this expectation matches the message with any argument (default) * with_no_args Declares that this expectation matches messages with no arguments * and_return(value) Declares that the expected message will return the given value. * and_return(value1, value2, ...) Declares that the expected message will return a series of values. Each invocation of the message will return the next value in the series. The last value will be repeatably returned if the number of matching calls exceeds the number of values. * and_return { |args, ...| code ... } Declares that the expected message will return the yielded value of the block. The block will receive all the arguments in the message. If the message was provided a block, it will be passed as the last parameter of the block's argument list. * returns( ... ) Alias for and_return. * and_raise(exception, *args) Declares that the expected messsage will raise the specified exception. If +exception+ is an exception class, then the raised exception will be constructed from the class with +new+ given the supplied arguments. If +exception+ is an instance of an exception class, then it will be raised directly. * raises( ... ) Alias for and_raise. * and_throw(symbol) * and_throw(symbol, value) Declares that the expected messsage will throw the specified symbol. If an optional value is included, then it will be the value returned from the corresponding catch statement. * throws( ... ) Alias for and_throw. * and_yield(values, ...) Declares that the mocked method will receive a block, and the mock will call that block with the values given. Not providing a block will be an error. Providing more than one +and_yield+ clause one a single expectation will mean that subsquent mock method calls will yield the values provided by the additional +and_yield+ clause. * yields( ... ) Alias for and_yield( ... ). * zero_or_more_times Declares that the expected message is may be sent zero or more times (default, equivalent to at_least.never). * once Declares that the expected message is only sent once. at_least / at_most modifiers are allowed. * twice Declares that the expected message is only sent twice. at_least / at_most modifiers are allowed. * never Declares that the expected message is never sent. at_least / at_most modifiers are allowed. * times(n) Declares that the expected message is sent n times. at_least / at_most modifiers are allowed. * at_least Modifies the immediately following message count constraint so that it means the message is sent at least that number of times. E.g. at_least.once means the message is sent at least once during the test, but may be sent more often. Both at_least and at_most may be specified on the same expectation. * at_most Similar to at_least, but puts an upper limit on the number of messages. Both at_least and at_most may be specified on the same expectation. * ordered Declares that the expected message is ordered and is expected to be received in a certain position in a sequence of messages. The message should arrive after and previously declared ordered messages and prior to any following declared ordered messages. Unordered messages are ignored when considering the message order. Normally ordering is performed only against calls in the same mock object. If the "globally" adjective is used, then ordering is performed against the other globally ordered method calls. * ordered(group) Declare that the expected message belongs to an order group. Methods within an order group may be received in any order. Ordered messages outside the group must be received either before or after all of the grouped messages. For example, in the following, messages +flip+ and +flop+ may be received in any order (because they are in the same group), but must occur strictly after +start+ but before +end+. The message +any_time+ may be received at any time because it is not ordered. m = flexmock() m.should_receive(:any_time) m.should_receive(:start).ordered m.should_receive(:flip).ordered(:flip_flop_group) m.should_receive(:flop).ordered(:flip_flop_group) m.should_receive(:end).ordered Normally ordering is performed only against calls in the same mock object. If the "globally" adjective is used, then ordering is performed against the other globally ordered method calls. * globally.ordered * globally.ordered(group_name) When modified by the "globally" adjective, the mock call will be ordered against other globally ordered methods in any of the mock objects in the same container (i.e. same test). All the options of the per-mock ordering are available in the globally ordered method calls. * by_default Marks the expectation as a default. Default expectations act as normal as long as there are no non-default expectations for the same method name. As soon as a non-default expectation is defined, all default expectations for that method name are ignored. Default expectations allow you to setup a set of default behaviors for various methods in the setup of a test suite, and then override only the methods that need special handling in any given test. * mock Expectation constraints always return the expectation so that the constraints can be chained. If you wish to do a one-liner and assign the mock to a variable, the +mock+ method on an expectation will return the original mock object. m = flexmock.should_receive(:hello).once.and_return("World").mock NOTE: Using mock when specifying a Demeter mock chain will return the last mock of the chain, which might not be what you expect. === Argument Validation The values passed to the +with+ declarator determine the criteria for matching expectations. The first expectation found that matches the arguments in a mock method call will be used to validate that mock method call. The following rules are used for argument matching: * A +with+ parameter that is a class object will match any actual argument that is an instance of that class. Examples: with(Integer) will match f(3) * A regular expression will match any actual argument that matches the regular expression. Non-string actual arguments are converted to strings via +to_s+ before applying the regular expression. Examples: with(/^src/) will match f("src_object") with(/^3\./) will match f(3.1415972) * Most other objects will match based on equal values. Examples: with(3) will match f(3) with("hello") will match f("hello") * If you wish to override the default matching behavior and force matching by equality, you can use the FlexMock.eq convenience method. This is mostly used when you wish to match class objects, since the default matching behavior for class objects is to match instances, not themselves. Examples: with(eq(Integer)) will match f(Integer) with(eq(Integer)) will NOT match f(3) Note: If you do not use the FlexMock::TestCase Test Unit integration module, or the FlexMock::ArgumentTypes module, you will have to fully qualify the +eq+ method. This is true of all the special argument matches (+eq+, +on+, +any+, +hsh+ and +ducktype+). with(FlexMock.eq(Integer)) with(FlexMock.on { code }) with(FlexMock.any) with(FlexMock.hsh(:tag => 3)) with(FlexMock.ducktype(:wag => "dog")) * If you wish to match a hash on _some_ of its values, the FlexMock.hsh(...) method will work. Only specify the hash values you are interested in, the others will be ignored. with(hsh(:run => true)) will match f(:run => true, :stop => false) * If you wish to match any object that responds to a certain set of methods, use the FlexMock.ducktype method. with(ducktype(:to_str)) will match f("string") with(ducktype(:wag, :bark)) will match f(dog) (assuming dog implements wag and bark) * If you wish to match _anything_, then use the FlexMock.any method in the with argument list. Examples (assumes either the FlexMock::TestCase or FlexMock::ArgumentTypes mix-ins has been included): with(any) will match f(3) with(any) will match f("hello") with(any) will match f(Integer) with(any) will match f(nil) * If you wish to specify a complex matching criteria, use the FlexMock.on(&block) with the logic contained in the block. Examples (assumes FlexMock::ArgumentTypes has been included): with(on { |arg| (arg % 2) == 0 } ) will match any even integer. * If you wish to match a method call where a block is given, add Proc as the last argument to with. Example: m.should_receive(:foo).with(Integer,Proc).and_return(:got_block) m.should_receive(:foo).with(Integer).and_return(:no_block) will cause the mock to return the following: m.foo(1) { } => returns :got_block m.foo(1) => returns :no_block === Creating Partial Mocks Sometimes it is useful to mock the behavior of one or two methods in an existing object without changing the behavior of the rest of the object. If you pass a real object to the +flexmock+ method, it will allow you to use that real object in your test and will just mock out the one or two methods that you specify. For example, suppose that a Dog object uses a Woofer object to bark. The code for Dog looks like this (we will leave the code for Woofer to your imagination): class Dog def initialize @woofer = Woofer.new end def bark @woofer.woof end def wag :happy end end Now we want to test Dog, but using a real Woofer object in the test is a real pain (why? ... well because Woofer plays a sound file of a dog barking, and that's really annoying during testing). So, how can we create a Dog object with mocked Woofer? All we need to do is allow FlexMock to replace the +bark+ method. Here's the test code: class TestDogBarking < Test::Unit::TestCase include FlexMock::TestCase # Setup the tests by mocking the +new+ method of # Woofer and return a mock woofer. def setup @dog = Dog.new flexmock(@dog, :bark => :grrr) end def test_dog assert_equal :grrr, @dog.bark # Mocked Method assert_equal :happy, @dog.wag # Normal Method end end The nice thing about this technique is that after the test is over, the mocked out methods are returned to their normal state. Outside the test everything is back to normal. NOTE: In previous versions of FlexMock, partial mocking was called "stubs" and the +flexstub+ method was used to create the partial mocks. Although partial mocks were often used as stubs, the terminology was not quite correct. The current version of FlexMock uses the +flexmock+ method to create both regular stubs and partial stubs. A version of the +flexstub+ method is included for backwards compatibility. See Martin Fowler's article Mocks Aren't Stubs (http://www.martinfowler.com/articles/mocksArentStubs.html) for a better understanding of the difference between mocks and stubs. This partial mocking technique was inspired by the +Stuba+ library in the +Mocha+ project. === Mocking Class Objects In the previous example we mocked out the +bark+ method of a Dog object to avoid invoking the Woofer object. Perhaps a better technique would be to mock the Woofer object directly. But Dog uses Woofer explicitly so we cannot just pass in a mock object for Dog to use. But wait, we can add mock behavior to any existing object, and classes are objects in Ruby. So why don't we just mock out the Woofer class object to return mocks for us. class TestDogBarking < Test::Unit::TestCase include FlexMock::TestCase # Setup the tests by mocking the +new+ method of # Woofer and return a mock woofer. def setup flexmock(Woofer).should_receive(:new). and_return(flexmock(:woof => :grrr)) @dog = Dog.new end def test_dog assert_equal :grrrr, @dog.bark # Calls woof on mock object # returned by Woofer.new end end === Mocking Behavior in All Instances Created by a Class Object Sometimes returning a single mock object is not enough. Occasionally you want to mock every instance object created by a class. FlexMock makes this very easy. class TestDogBarking < Test::Unit::TestCase include FlexMock::TestCase # Setup the tests by mocking Woofer to always # return partial mocks. def setup flexmock(Woofer).new_instances.should_receive(:woof => :grrr) end def test_dog assert_equal :grrrr, Dog.new.bark # All dog objects assert_equal :grrrr, Dog.new.bark # are mocked. end end Note that FlexMock adds the mock expectations after the original +new+ method has completed. If the original version of +new+ yields the newly created instance to a block, that block will get an non-mocked version of the object. Note that +new_instances+ will accept a block if you wish to mock several methods at the same time. E.g. flexmock(Woofer).new_instances do |m| m.should_receive(:woof).twice.and_return(:grrr) m.should_receive(:wag).at_least.once.and_return(:happy) end === Default Expectations on Mocks Sometimes you want to setup a bunch of default expectations that are pretty much for a number of different tests. Then in the individual tests, you would like to override the default behavior on just that one method you are testing at the moment. You can do that by using the by_default modifier. In your test setup you might have: def setup @mock_dog = flexmock("Fido") @mock_dog.should_receive(:tail => :a_tail, :bark => "woof").by_default end The behaviors for :tail and :bark are good for most of the tests, but perhaps you wish to verify that :bark is called exactly once in a given test. Since :bark by default has no count expectations, you can override the default in the given test. def test_something_where_bark_must_be_called_once @mock_dog.should_receive(:bark => "woof").once # At this point, the default for :bark is ignored, # and the "woof" value will be returned. # However, the default for :tail (which returns :a_tail) # is still active. end By setting defaults, your individual tests don't have to concern themselves with details of all the default setup. But the details of the overrides are right there in the body of the test. === Mocking Law of Demeter Violations The Law of Demeter says that you should only invoke methods on objects to which you have a direct connection, e.g. parameters, instance variables, and local variables. You can usually detect Law of Demeter violations by the excessive number of periods in an expression. For example: car.chassis.axle.universal_joint.cog.turn The Law of Demeter has a very big impact on mocking. If you need to mock the "turn" method on "cog", you first have to mock chassis, axle, and universal_joint. # Manually mocking a Law of Demeter violation cog = flexmock("cog") cog.should_receive(:turn).once.and_return(:ok) joint = flexmock("gear", :cog => cog) axle = flexmock("axle", :universal_joint => joint) chassis = flexmock("chassis", :axle => axle) car = flexmock("car", :chassis => chassis) Yuck! The best course of action is to avoid Law of Demeter violations. Then your mocking exploits will be very simple. However, sometimes you have to deal with code that already has a Demeter chain of method calls. So for those cases where you can't avoid it, FlexMock will allow you to easily mock Demeter method chains. Here's an example of Demeter chain mocking: # Demeter chain mocking using the short form. car = flexmock("car") car.should_receive( "chassis.axle.universal_joint.cog.turn" => :ok).once You can also use the long form: # Demeter chain mocking using the long form. car = flexmock("car") car.should_receive("chassis.axle.universal_joint.cog.turn").once. and_return(:ok) That's it. Anywhere FlexMock accepts a method name for mocking, you can use a demeter chain and FlexMock will attempt to do the right thing. But beware, there are a few limitations. The all the methods in the chain, except for the last one, will mocked to return a mock object. That mock object, in turn, will be mocked so as to respond to the next method in the chain, returning the following mock. And so on. If you try to manually mock out any of the chained methods, you could easily interfer with the mocking specified by the Demeter chain. FlexMock will attempt to catch problems when it can, but there are certainly scenarios where it cannot detect the problem beforehand. == Examples === Create a simple mock object that returns a value for a set of method calls require 'flexmock/test_unit' class TestSimple < Test::Unit::TestCase def test_simple_mock m = flexmock(:pi => 3.1416, :e => 2.71) assert_equal 3.1416, m.pi assert_equal 2.71, m.e end end === Create a mock object that returns an undefined object for method calls require 'flexmock/test_unit' class TestUndefined < Test::Unit::TestCase def test_undefined_values m = flexmock("mock") m.should_receive(:divide_by).with(0). and_return_undefined assert_equal FlexMock.undefined, m.divide_by(0) end end === Expect multiple queries and a single update Multiple calls to the query method will be allows, and calls may have any argument list. Each call to query will return the three element array [1, 2, 3]. The call to update must have a specific argument of 5. require 'flexmock/test_unit' class TestDb < Test::Unit::TestCase def test_db db = flexmock('db') db.should_receive(:query).and_return([1,2,3]) db.should_receive(:update).with(5).and_return(nil).once # test code here end end === Expect all queries before any updates (This and following examples assume that the 'flexmock/test_unit' file has been required.) All the query message must occur before any of the update messages. def test_query_and_update db = flexmock('db') db.should_receive(:query).and_return([1,2,3]).ordered db.should_receive(:update).and_return(nil).ordered # test code here end === Expect several queries with different parameters The queries should happen after startup but before finish. The queries themselves may happen in any order (because they are in the same order group). The first two queries should happen exactly once, but the third query (which matches any query call with a four character parameter) may be called multiple times (but at least once). Startup and finish must also happen exactly once. Also note that we use the +with+ method to match different argument values to figure out what value to return. def test_ordered_queries db = flexmock('db') db.should_receive(:startup).once.ordered db.should_receive(:query).with("CPWR").and_return(12.3). once.ordered(:queries) db.should_receive(:query).with("MSFT").and_return(10.0). once.ordered(:queries) db.should_receive(:query).with(/^....$/).and_return(3.3). at_least.once.ordered(:queries) db.should_receive(:finish).once.ordered # test code here end === Same as above, but using the Record Mode interface The record mode interface offers much the same features as the +should_receive+ interface introduced so far, but it allows the messages to be sent directly to a recording object rather than be specified indirectly using a symbol. def test_ordered_queries_in_record_mode db = flexmock('db') db.should_expect do |rec| rec.startup.once.ordered rec.query("CPWR") { 12.3 }.once.ordered(:queries) rec.query("MSFT") { 10.0 }.once.ordered(:queries) rec.query(/^....$/) { 3.3 }.at_least.once.ordered(:queries) rec.finish.once.ordered end # test code here using +db+. end === Using Record Mode to record a known, good algorithm for testing Record mode is nice when you have a known, good algorithm that can use a recording mock object to record the steps. Then you compare the execution of a new algorithm to behavior of the old using the recorded expectations in the mock. For this you probably want to put the recorder in _strict_ mode so that the recorded expectations use exact matching on argument lists, and strict ordering of the method calls. Note: This is most useful when there are no queries on the mock objects, because the query responses cannot be programmed into the recorder object. def test_build_xml builder = flexmock('builder') builder.should_expect do |rec| rec.should_be_strict known_good_way_to_build_xml(rec) # record the messages end new_way_to_build_xml(builder) # compare to new way end === Expect multiple calls, returning a different value each time Sometimes you need to return different values for each call to a mocked method. This example shifts values out of a list for this effect. def test_multiple_gets file = flexmock('file') file.should_receive(:gets).with_no_args. and_return("line 1\n", "line 2\n") # test code here end === Ignore uninteresting messages Generally you need to mock only those methods that return an interesting value or wish to assert were sent in a particular manner. Use the +should_ignore_missing+ method to turn on missing method ignoring. def test_an_important_message m = flexmock('m') m.should_receive(:an_important_message).and_return(1).once m.should_ignore_missing # test code here end When +should_ignore_missing+ is enabled, ignored missing methods will return an undefined object. Any operation on the undefined object will return the undefined object. === Mock just one method on an existing object The Portfolio class calculate the value of a set of stocks by talking to a quote service via a web service. Since we don't want to use a real web service in our unit tests, we will mock the quote service. def test_portfolio_value flexmock(QuoteService).new_instances do |m| m.should_receive(:quote).and_return(100) end port = Portfolio.new value = port.value # Portfolio calls QuoteService.quote assert_equal 100, value end == Other Mock Objects test-unit-mock :: http://www.deveiate.org/code/Test-Unit-Mock.shtml mocha/stubba :: http://mocha.rubyforge.org/ Schmock :: http://rubyforge.org/projects/schmock/ == License Copyright 2003, 2004, 2005, 2006, 2007 by Jim Weirich (jim@weirichhouse.org). All rights reserved. Permission is granted for use, copying, modification, distribution, and distribution of modified versions of this work as long as the above copyright notice is included. = Other stuff Author:: Jim Weirich Requires:: Ruby 1.8.7 or later (Use Flexmock-0.8.8 for Ruby version 1.8.6) == Warranty This software is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantibility and fitness for a particular purpose. flexmock-0.9.0/Rakefile0000644000175000017500000001027011661521733015214 0ustar terceiroterceiro# Rakefile for flexmock -*- ruby -*- #--- # Copyright 2003, 2004, 2005, 2006, 2007 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ task :noop require 'rubygems' require 'rake/clean' require 'rake/testtask' require 'rake/contrib/rubyforgepublisher' require 'rubygems/package_task' CLEAN.include('*.tmp') CLOBBER.include("html", 'pkg') load './lib/flexmock/version.rb' PKG_VERSION = FlexMock::VERSION PKG_FILES = FileList[ '[A-Z]*', 'lib/**/*.rb', 'test/**/*.rb', '*.blurb', 'install.rb' ] RDOC_FILES = FileList[ 'README.rdoc', 'CHANGES', 'lib/**/*.rb', 'doc/**/*.rdoc', ] task :default => [:test_all] task :test_all => [:test] task :test_units => [:test] task :ta => [:test_all] # Test Targets ------------------------------------------------------- Rake::TestTask.new do |t| t.test_files = FileList['test/*_test.rb'] t.libs << "." t.verbose = false t.warning = true end Rake::TestTask.new(:test_extended) do |t| t.test_files = FileList['test/extended/*_test.rb'] t.verbose = true t.warning = true end task :rspec do ENV['RUBYLIB'] = "/Users/jim/working/svn/software/flexmock/lib" sh 'echo $RUBYLIB' sh "spec test/rspec_integration/*_spec.rb" rescue nil puts puts "*** There should be three failures in the above report. ***" puts end # RCov Target -------------------------------------------------------- begin require 'rcov/rcovtask' Rcov::RcovTask.new do |t| t.libs << "test" t.rcov_opts = ['-xRakefile', '-xrakefile', '-xpublish.rf', '-x/Lib*', '--text-report', '--sort', 'coverage'] t.test_files = FileList['test/test*.rb'] t.verbose = true end rescue LoadError => ex end # RDoc Target -------------------------------------------------------- task :rdoc => ["html/index.html"] file "html/index.html" => ["Rakefile"] + RDOC_FILES do sh "rdoc -o html --title FlexMock --line-numbers -m README.rdoc #{RDOC_FILES}" end file "README.rdoc" => ["Rakefile", "lib/flexmock/version.rb"] do ruby %{-i.bak -pe '$_.sub!(/^Version *:: *(\\d+\\.)+\\d+ *$/, "Version :: #{PKG_VERSION}")' README.rdoc} # " end # Package Task ------------------------------------------------------- if ! defined?(Gem) puts "Package Target requires RubyGEMs" else spec = Gem::Specification.new do |s| #### Basic information. s.name = 'flexmock' s.version = PKG_VERSION s.summary = "Simple and Flexible Mock Objects for Testing" s.description = %{ FlexMock is a extremely simple mock object class compatible with the Test::Unit framework. Although the FlexMock's interface is simple, it is very flexible. } # ' #### Dependencies and requirements. #s.add_dependency('log4r', '> 1.0.4') #s.requirements << "" #### Which files are to be included in this gem? Everything! (Except CVS directories.) s.files = PKG_FILES.to_a #### C code extensions. #s.extensions << "ext/rmagic/extconf.rb" #### Load-time details: library and application (you will need one or both). s.require_path = 'lib' # Use these for libraries. #### Documentation and testing. s.has_rdoc = true s.extra_rdoc_files = RDOC_FILES.reject { |fn| fn =~ /\.rb$/ }.to_a s.rdoc_options << '--title' << 'FlexMock' << '--main' << 'README.rdoc' << '--line-numbers' #### Author and project details. s.author = "Jim Weirich" s.email = "jim.weirich@gmail.com" s.homepage = "https://github.com/jimweirich/flexmock" end Gem::PackageTask.new(spec) do |pkg| pkg.need_zip = true pkg.need_tar = false end end require 'rake/contrib/publisher' require 'rake/contrib/sshpublisher' publisher = Rake::CompositePublisher.new publisher.add(Rake::RubyForgePublisher.new('flexmock', 'jimweirich')) desc "Publish the documentation on public websites" task :publish => [:rdoc] do publisher.upload end task :specs do specs = FileList['test/spec_*.rb'] ENV['RUBYLIB'] = "lib:test:#{ENV['RUBYLIB']}" sh %{rspec #{specs}} end task :tag do sh "git tag 'flexmock-#{PKG_VERSION}'" end flexmock-0.9.0/CHANGES0000644000175000017500000001344111661521733014545 0ustar terceiroterceiro= Changes for FlexMock == Version 0.8.5 * Fixed warning about a void context. * hsh() argument matcher now reports its matching constraints in error messages. == Version 0.8.4 * Added support for rails 2.2.x in should_render_view. == Version 0.8.3 * Fixed a bug where the by_default option was not completely honored in some edge cases. == Version 0.8.2 * Added workaround for compatibility issues with RSpec on Rails. == Version 0.8.1 * Additional fix for Rails 2.0.2 * Added Joe O'Brien's patch to allow view stubbing in Rails 2.0 * Added Evan Phoenix's patch to remove allocate from default allocators in new_instances (for Rubinius compatibility). == Version 0.8.0 * Added by_default * Added undefined behavior * Mock methods are added to partial mocks only if they are not previously defined. This should reduce the need for safe mode. * respond_to? on mocks now accepts multiple arguments. This eases mocking in rails a little bit. * Added experimental view mocking for rails. == Version 0.7.2 * Changed initial model Id to 10000. * Added test suggested for RSpec Mocks, just to make sure we were good too. == Version 0.7.1 * Updated install.rb to handle non-root destination directories via DESTDIR. * Fixed operator bug introduced in 0.7.0. == Version 0.7.0 * Added +and_yield+ as an expectation clause. * Inspect on Mocks now yield a more consise description. * Global ordering across all mocks in a container is now allowed. * Added support for Demeter chain mocking. * Deprecated a number of mock_* methods. == Version 0.6.4 * Renamed flexmodel(...) to flexmock(:model, ...) because visually they were too similar. == Version 0.6.3 * Added flexmodel() for better support of mocking ActiveRecord models. * Fixed comment for singleton? * Fixed coverage report for the partial mocking class. * Fixed bug when partial mock objects reported they respond to a method but they actually didn't. * The flexmock() method now _always_ returns a combination domain/mock object. For partial mocks, this implies that the domain object now has mock support methods on it (e.g. should_receive). * Safe mode for partials was introduced for the small number of cases where mock support methods in the domain object would cause problems. * Internally renamed PartialMock to PartialMockProxy. == Version 0.6.2 * flexmock() with a block now always returns the domain object. flexmock() without a block returns the mock object. Note that for normal mocks, the domain and mock objects are the same. For partial mocks, the mock is separate from the domain object. * Added +and_raise+ to the list of expection specifications. == Version 0.6.1 * Fixed bug that prevented mocks from mocking field assignment operators. * Fixed bug that prevented partial mocks from being ordered. == Version 0.6.0 * Dropped class interception. * Refactored into more granular classes. * Added RSpec integration. * Added hash expectations to flexmock() and should_expect(). * Integrated partial mocks into the flexmock() methods. * Allow non-block configuration of new_instances. == Version 0.5.1 * Changed the name of any_instance to new_instances. Deprecated any_instance. * Added ability to stub any class method in new_instances. * Added RCov task * Reworked original behavior hooks to use method aliasing rather than method procs. * Fixed bug in stubbing File class methods. == Version 0.5.0 * Added any_instance stubbing to class objects. == Version 0.4.5 * Fixed version typo in 0.4.4 (internally claimed to be 0.4.3.1) == Version 0.4.4 * Added block support to flexstub. == Version 0.4.3 * Fixed bug where non-direct class methods were not properly handled. == Version 0.4.2 * Fixed bug where multiple stubs of a class method were not properly restored. == Version 0.4.1 * Removed include of Test::Unit::Assertions from Expectations. * Fixed mocking of kernel methods. == Version 0.4.0 * Added stubbing for mocking methods of existing objects. * Added multiple return values for the +and_returns+ method. * Added block initialization to the flexmock method. == Version 0.3.2 * Fixed bug when mock is used as a replacement class in class interception. == Version 0.3.1 * Fixed some warnings regarding uninitialized variables. * Added (very) simple class interception. * Added the mock_factory method to go along with class interception. * When using Test::Unit integration, avoid mock verification if the test has already failed for some reason. == Version 0.3.0 * Added Test::Unit integration. == Version 0.2.1 * Added strict mode in record mode interface to facility using known good algorithms for comparison testing. * Improved the docs and examples. Fixed garbled first example in README. == Version 0.2.0 * Added record mode for building expectations. * Fixed a bunch of documentation. == Version 0.1.7 * Bumped version because 0.1.6 was uploaded to the wrong Rubyforge area. == Version 0.1.6 * Added a proc based matcher for arguments (using keyword +on+). == Version 0.1.5 * Fixed the overzealous argument matching when String is given as an argument qualifier to +should_receive+. == Version 0.1.4 * Added eq and any methods for argument matching. * Added tests for the "first match" argument matching policy. == Version 0.1.3 * Improved the definition of ordered so that it takes group names instead of explicit order numbers. This make the code easier to write and the API easier to understand. == Version 0.1.2 * Fixed homepage in gem spec. * Removed autorequire from gemspec. * Fixed README to be automatically updated with FlexMock Version == Version 0.1.1 * Added responds_to? and method support. * Added JMock style expectations. == Version 0.0.3 * Changed to a GEM package. == Version 0.0.2 * Updated the documentation. * Fixed the install script. == Version 0.0.1 * Initial Version