首页 > 解决方案 > 如何允许在控制器中模拟本地范围的变量以接收消息?

问题描述

所以,我只做 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-railsrubyrspec

解决方案


你可能想要这个:

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=(注意)。=


推荐阅读