找出编写RSpec测试的计划

时间:2013-02-24 16:57:59

标签: ruby-on-rails rspec

我有一个控制器如下:

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的基本知识,但是这整个周末让我感到困惑。

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分: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