RSpec-Rails - 存根控制器变量

RSpec-Rails - stub a controller variable

我有一个要测试的控制器动作:

LOG = ApiRequest::Resource::Login

def create
    @response = LOG.new(current_user, params: params).create
    return if request_failed?
    ...
end

def request_failed?
    if @response.is_a? Hash
      false
    else
      error = @response
      redirect_to new_login_path, alert: error
      true
    end
  end

LOG.new(current_user, params: params).create 是一个外部 api 调用,通常 returns 是哈希值或带有错误的字符串。我想在不触发调用的情况下测试控制器操作,例如 force @response = {} 并检查它是否不重定向并强制 @response = "" 应该触发重定向。

it 'redirects if fails the request' do
    post :create
    expect(response).to redirect_to new_login_path
    expect(flash[:alert]).not_to be nil
end

如何存根实例变量?

我会用存根 LOG 实例来测试它,比如:

let(:log_instance) { instance_double(LOG) }

before do
  allow(LOG).to receive(:new).and_return(log_instance)
  allow(log_instance).to receive(:create).and_return({})
end