【问题标题】:How do I allow mock a locally scoped variable in a controller to receive a message?如何允许在控制器中模拟本地范围的变量以接收消息?
【发布时间】:2021-08-26 15:48:22
【问题描述】:

所以,我只做 Ruby 几天。任何提示将不胜感激。

变量.rb

class Variable < ApplicationRecord
  def some_attribute=(value)
    #do something with the vlue
  end
end

X_Controller.rb

class XController < ApplicationController
  def do_something
    variable = Variable.instance_with_id(params[:id])
    variable.some_attribute = some_new_value
    redirect_to(some_url)
  end
end

x_controller_spec.rb

describe '#do_something' do
  before do
    allow(Variable).to receive(:instance_with_id) # Works fine
    allow_any_instance_of(Variable).to receive(:some_attribute)
    
    post :do_something, :params => { id: 'uuid' }, :format => :json 
  end

  it { 
    expect(variable).to have_received(:some_attribute)
  }
end

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    你可能想要这个:

    let(:variable) { instance_double("Variable") }
    
    before do
      allow(Variable).to receive(:instance_with_id).and_return(variable)
      allow(variable).to receive(:some_attribute=)
    
      # ...
    end
    

    因为instance_with_id 应该返回一些东西。然后你想允许在那个实例上调用some_attribute=(注意=)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2023-01-24
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多