【问题标题】:Expect mock to receive message in rails controller期望模拟在 Rails 控制器中接收消息
【发布时间】:2013-11-28 04:10:50
【问题描述】:

我无法为我的一个控制器中使用的模拟设置期望:

控制器/blak_controller.rb

class BlarkController < ApplicationController
  def show
    user = User.first
    user.inspect
    render nothing: true
  end
end

spec/controllers/blark_controller_spec.rb

require 'spec_helper'

describe BlarkController do
  describe 'GET :show' do

    let(:user) { mock_model User }

    before do
      User.stub(:first).and_return(user)
      get :show
    end

    it 'blarks' do
      expect(user).to receive(:inspect)
    end

  end
end

结果如下:

22:04:58 - INFO - Running: spec/controllers/blark_controller_spec.rb

BlarkController
  GET :show
    blarks (FAILED - 1)

Failures:

  1) BlarkController GET :show blarks
     Failure/Error: expect(user).to receive(:inspect)
       (Double "User_1001").inspect(any args)
           expected: 1 time with any arguments
           received: 0 times with any arguments
     # ./spec/controllers/blark_controller_spec.rb:14:in `block (3 levels) in <top (required)>'

Finished in 0.15579 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/controllers/blark_controller_spec.rb:13 # BlarkController GET :show blarks

我可以在规范中设定对模拟的期望吗?

【问题讨论】:

    标签: ruby-on-rails unit-testing rspec


    【解决方案1】:

    你可以,但你这样做的方式是错误的。

    您正在调用一个动作 (get :show),然后在调用它之后,设置一个未来的期望 (expect(user).to receive(:inspect))。显然这行不通,因为你已经调用了这个动作,这个测试没有未来。

    您需要在调用操作之前设置期望(切换语句的顺序)或使用 rspec 最近添加的间谍功能在事后设置期望。这使用have_received 而不是receive

    更多详情:https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/spies/spy-on-a-stubbed-method-on-a-partial-mock

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2022-12-03
      • 1970-01-01
      • 2021-12-13
      相关资源
      最近更新 更多