RSpec中mock和mock_model有什么区别

时间:2009-08-12 01:26:12

标签: ruby-on-rails ruby testing rspec

我最近遇到过不同的教程,人们同时使用 mock mock_model 功能。

RSpec tutorial for controllers中,他们使用 mock_model 功能,但在documentation of RSpec中,只有 mock 功能,但没有 mock_model

我试图自己运行一些测试,但我没有发现任何真正的区别,因为当我使用这两个函数中的任何一个时一切正常,所以有什么不同吗?

2 个答案:

答案 0 :(得分:33)

正如jenger所说,mock_model是为活动记录而构建的扩展:

这是1.2.6中的来源:

     def mock_model(model_class, options_and_stubs = {})
        id = options_and_stubs[:id] || next_id
        options_and_stubs = options_and_stubs.reverse_merge({
          :id => id,
          :to_param => id.to_s,
          :new_record? => false,
          :errors => stub("errors", :count => 0)
        })
        m = mock("#{model_class.name}_#{id}", options_and_stubs)
        m.__send__(:__mock_proxy).instance_eval <<-CODE
          def @target.as_new_record
            self.stub!(:id).and_return nil
            self.stub!(:to_param).and_return nil
            self.stub!(:new_record?).and_return true
            self
          end
          def @target.is_a?(other)
            #{model_class}.ancestors.include?(other)
          end
          def @target.kind_of?(other)
            #{model_class}.ancestors.include?(other)
          end
          def @target.instance_of?(other)
            other == #{model_class}
          end
          def @target.class
            #{model_class}
          end
        CODE
        yield m if block_given?
        m
      end

所以它非常满口,但它

  • 将id与序列中的下一个存根
  • 存根to_param
  • stubs new_record?假的
  • 存根错误,因此它认为没有错误

它还使用一堆东西扩展了模型实例。

答案 1 :(得分:9)

来自:Useful helpers for RSpec mocks

  

首先,mock_model自动进行   为模型定义唯一ID   是用它创造的。其次,它   定义方法to_param(返回   id)和。的字符串表示   new_record?(返回false)。