使用rspec确认函数在控制器中调用

时间:2013-08-13 21:47:50

标签: ruby-on-rails rspec

我正在尝试确认在带有rspec测试的控制器方法中调用了一个函数。为此,我正在关注confirming an instance of a class receives a message的relishapp文档。我的实现如下:但是,我不断收到以下错误:

  it "does the job" do
    expect {
      post :create, {:obj => valid_attributes}
    }.to change(Object, :count).by(1)
    Object.any_instance.should_receive(:delay)
    flash[:notice].should eq(I18n.t(:success, obj: 'object', past_participle: 'created'))
    response.should redirect_to(new_object_path)
  end

但是,我一直收到以下错误:

Failure/Error: Unable to find matching line from backtrace
   Exactly one instance should have received the following message(s) but didn't: delay

在这种情况下,我正在尝试确认调用delay方法。我可以清楚地看到在控制器方法中调用该方法,为什么rspec不确认呢?

1 个答案:

答案 0 :(得分:1)

正如我所看到的,有两种方法来测试这种行为。

正如延迟作业文档所示,您可以使用cio_register()忽略Delayed::Worker.delay_jobs = false方法的延迟。我相信这是因为我们可以安全地假设延迟工作会起作用。

我会按如下方式重新编写测试:

describe '#create'
  it 'creates a new Object' do
    expect {
      post :create, {:object => valid_attributes}
    }.to change(Object, :count).by(1)
  end

  it 'performs CIO registration on new object' do
    # Skip Delayed Jobs.
    original_setting = Delayed::Worker.delay_jobs
    Delayed::Worker.delay_jobs = false

    # Our expectation.
    Object.any_instance.should_receive(:cio_register)

    post :create, {:object => valid_attributes}

    # Restore Delayed Job's setting.
    Delayed::Worker.delay_jobs = original_setting
  end

  it 'sets appropriate flash message'
  it 'redirects to path showing details of newly created Object'
end

如果延迟对方法的行为至关重要,您可以在测试中完成工作并确保其结果:

it 'performs CIO registration on new object' do
  # Our expectation.
  Object.any_instance.should_receive(:cio_register)

  post :create, {:object => valid_attributes}

  # Let's process the delayed job.
  Delayed::Worker.new.work_off
end

我在google搜索时找到了这个有趣的条目:http://artsy.github.io/blog/2012/08/16/testing-with-delayed-jobs/