1

我有一个控制器如下:

class ReportsController < ApplicationController
    respond_to :html
  def show
    client = ReportServices::Client.new(ServiceConfig['reports_service_uri'])
    @report = client.population_management(params[:id])
    if @report
      @kpis = @report[:key_performance_indicators]
      @populations = @report[:population_scores]
      @population_summaries = @report[:population_summaries]
      @providers = @report[:provider_networks]
    end
    respond_with (@report)   
  end
end

我想为它写一个 RSpec 测试,但不知道从哪里开始,我猜是因为它里面有那个 URL,这让我更难,我对 Rails 和 RSpec 还很陌生,并且有一些基本知识为我的模型编写 RSpec 但这一个让我整个周末都感到困惑。

4

2 回答 2

1

您可以存根客户端接口以编写控制器的隔离测试。

describe RerpotsController do
  it "assigns a new report as @report" do
    expected_id = '1234'
    expected_kpi = 'kpi'

    report = { key_performance_indicators: expected_kpi, ... }
    client = double(ReportServices::Client)
    client.should_receive(:population_management).with(expected_id) { report }
    ReportServices::Client.should_receive(:new) { client }

    get :show, id: expected_id

    assigns(:kpis).should eq(expected_kpi)
    # ...
  end
end

您可能不需要在控制器中解压报表。

于 2013-02-24T19:22:21.093 回答
1

所以首先要解决的是模拟外部 API 请求。这里的总体思路是,您将从 new 返回一个模拟对象,该对象将响应 population_management 并返回您对 @report 的期望。

describe ReportsController do
  before do
    @report_data = {
      :key_performance_indicators => 'value',
      :population_scores => 'value',
      :population_summaries => 'value',
      :provider_networks => 'value'
    }
    # This will fake the call to new, return a mock object that when
    # population_management is called will return the hash above.
    @fake_client = double(:population_management => @report_data)
    ReportServices::Client.stub(:new => @fake_client)
  end

  describe '#show' do
    it 'assigns @report' do
      get :show, id: 1
      assigns(:report).should == @report
    end

    it 'assigns some shortcut vars' do
      [:kpis, :populations, :population_summaries, :providers].each do |var|
        assigns(var).should_not be_nil
      end
    end

    # and whatever else you'd like
  end
end
于 2013-02-24T19:23:42.180 回答