AutoMocha example

Again – I’m not really very pleased with this example, but hopefully it makes some sense. It’s important to realise that the test is not running in a normal Rails environment with the standard auto-require. In fact the first time the Comment class is encountered AutoMocha uses const_missing to supply a Mocha::Mock in its place. From that point on – any further references get the same mock object.

class Article

    attr_reader :id

    def accepted_comments
      Comment.find_all_by_article_id( { |comment| comment.accepted? }


  require 'rubygems'
  require 'auto_mocha'
  require 'test/unit'

  class OrderTest < Test::Unit::TestCase

    include Mocha

    # illustrates stubbing of previously undefined class Comment
    def test_should_return_accepted_comments_for_this_article
      unaccepted_comment = => false)
      accepted_comment = => true)
      comments = [unaccepted_comment, accepted_comment]
      article =
      assert_equal [accepted_comment], article.accepted_comments