簡體   English   中英

Rspec在測試XML或CSV輸出時神秘地通過了

[英]Rspec mysteriously passes when testing XML or CSV output

在我的Rails 5應用程序中,我有以下內容:

class InvoicesController < ApplicationController

  def index
    @invoices = current_account.invoices
    respond_to do |format|
      format.csv do
        invoices_file(:csv)
      end
      format.xml do
        invoices_file(:xml)
      end
    end
  end

private

  def invoices_file(type)
    headers['Content-Disposition'] = "inline; filename=\"invoices.#{type.to_s}\""
  end

end

describe InvoicesController, :type => :controller do

  it "renders a csv attachment" do
    get :index, :params => {:format => :csv}
    expect(response.headers["Content-Type"]).to eq("text/csv; charset=utf-8")
    expect(response).to have_http_status(200)
    expect(response).to render_template :index
  end

end

我的問題是,即使我在index.csv.erb文件中放了一堆廢話,我的Spec總是通過 (!)。 似乎該視圖文件甚至沒有被RSpec評估/測試。

這怎么可能? 我在這里想念什么?

  1. 格式選項應在參數之外指定,即get :index, params: {}, format: :csv}

  2. 關於RSpec評估視圖,不對,在控制器測試中,不考慮其格式。 但是,可以使用RSpec測試視圖: https : //relishapp.com/rspec/rspec-rails/v/2-0/docs/view-specs/view-spec

控制器測試/規范是這些怪異的創意,它們是孤立地進行單元測試控制器的想法而產生的。 這個想法被證明是非常有缺陷的,並且最近真的不流行了。

控制器規范實際上並不向通過路由的應用程序發出真正的HTTP請求。 相反,他們只是偽造它並通過一個偽造的請求。

為了使測試更快,它們也不會真正渲染視圖。 這就是為什么它不會像您期望的那樣出錯的原因。 而且響應也不是真正的機架響應對象。

您可以使RSpec使用render_views呈現視圖。

describe InvoicesController, :type => :controller do
  render_views
  it "renders a csv attachment" do
    get :index, format: :csv
    expect(response.headers["Content-Type"]).to eq("text/csv; charset=utf-8")
    expect(response).to have_http_status(200)
    expect(response).to render_template :index
  end
end

但是更好的和更可靠的選擇是使用請求規范

Rails團隊和RSpec核心團隊的官方建議是編寫請求規范。 請求規范使您可以專注於單個控制器操作,但是與控制器測試不同,它涉及路由器,中間件堆棧以及機架的請求和響應。 這為您正在編寫的測試增加了真實感,並有助於避免控制器規范中常見的許多問題。 http://rspec.info/blog/2016/07/rspec-3-5-has-been-released/

# spec/requests/invoices
require 'rails_helper'
require 'csv'
RSpec.describe "Invoices", type: :request do
  let(:csv) { response.body.parse_csv }
  # Group by the route
  describe "GET /invoices" do
    it "renders a csv attachment" do
      get invoices_path, format: :csv
      expect(response.headers["Content-Type"]).to eq("text/csv; charset=utf-8")
      expect(response).to have_http_status(200)
      expect(csv).to eq ["foo", "bar"] # just an example
    end
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM