模拟如何工作 mocha gem?

How mocking works mocha gem?

我是 mocha 的新手 gem 之前我正在使用 minitest 来测试我的产品。然后我遇到了我的应用程序正在将工作发布到 facebook 的情况。它会选择一些工作,然后将它们发布到 facebook 上。 所以有人告诉我使用 mocking,我发现了 mocha gem。 我看到了一个样本测试。

  def test_mocking_an_instance_method_on_a_real_object
    job = Job.new
    job.expects(:save).returns(true)
    assert job.save
  end

But I did not get the idea. In my jobs controller, I have validations and the empty job cannot be saved successfully. But here with mocking the above test assert that job can be saved without mandatory fields.So what exactly we test in above test case?

通常这是一个很好的做法,原因如下:

从隔离的角度来看:控制器的职责是处理传入的请求并相应地触发动作。在我们给定的情况下,操作是:创建一个新工作,如果一切正常,则向 Facebook 发布一个新的 post。 (请注意我们的控制器不需要知道如何 post 到 FB)

想象一下以下控制器操作:

def create
  job = Job.new job_params

  if job.save
    FacebookService.post_job job
    ...
  else
    ...
  end
end

我会这样测试它:

class JobsControllerTest < ActionController::TestCase
  test "should create a job and issue new FB post" do
    job_params = { title: "Job title" }

    # We expect the post_job method will be called on the FacebookService class or module, and we replace the original implementation with an 'empty/mock' method that does nothing
    FacebookService.expects :post_job

    post :create, job_params

    assert_equal(Job.count, 1) # or similar
    assert_response :created
  end
end

另一个优点是:FacebookService.post_job 可能会花费大量时间,并且可能需要访问互联网等,我们不希望我们的测试挂起,特别是如果我们有 CI。

最后我会在 FacebookService 测试中测试真实的 FB posting,并且可能会删除一些其他方法,以防止在测试运行时每次都在 FB 上 posting (它需要时间、互联网、FB 帐户...)。