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(self.id).select { |comment| comment.accepted? }
    end

  end

  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 = Mock.new(:accepted? => false)
      accepted_comment = Mock.new(:accepted? => true)
      comments = [unaccepted_comment, accepted_comment]
      Comment.stubs(:find_all_by_article_id).returns(comments)
      article = Article.new
      assert_equal [accepted_comment], article.accepted_comments
    end

  end