RSpec中mock和mock_model有什么区别

Jak*_*old 34 ruby testing rspec ruby-on-rails

我最近遇到过不同的教程,人们使用它们mockmock_model功能.

控制器的RSpec教程中,他们使用该mock_model函数,但在RSpec文档中,只有mock函数,但没有mock_model

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

Sam*_*ron 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
Run Code Online (Sandbox Code Playgroud)

所以它非常满口,但它

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

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


小智 9

来自:RSpec模拟的有用助手

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