Như jenger nói mock_model là một phần mở rộng xây dựng cho kỷ lục hoạt động:
Đây là nguồn gốc trong 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
Vì vậy, nó khá một ngụm, nhưng nó
- lấy mẫu id tiếp theo theo thứ tự
- stubs to_param
- stubs new_record? với sai
- lỗi cuống nên nó nghĩ rằng không có lỗi
Nó cũng mở rộng các ví dụ mô hình với một loạt các công cụ.
Nguồn
2009-08-12 09:30:30
Đối với những người tìm kiếm xếp hạng câu hỏi này trong Google cho "rspec mock_model", tài liệu tốt nhất có thể được tìm thấy tại https://www.relishapp.com/rspec/rspec-rails/docs/mocks/mock-model –