1

我正在尝试使用 rspec 测试确认在控制器方法中调用了一个函数。为此,我按照 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方法已被调用。可以清楚的看到在controller方法中调用了方法,rspec为什么不确认呢?

4

1 回答 1

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

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

于 2013-08-14T12:31:26.547 回答