2016-09-16 115 views
7

我似乎無法通過此測試,我不明白爲什麼。Rspec send_data測試未通過

controller_spec.rb:

require 'rails_helper' 

RSpec.describe QuotationRequestsController, type: :controller do 

    describe "GET download" do  
    it "streams the sample text as a text file" do 
     #setup 
     quotation_request = create(:quotation_request) 
     file_options = {filename: "#{quotation_request.id}-#{quotation_request.client.name.parameterize}.txt", type: 'plain/text', disposition: 'attachment'} 

     #exercise 
     get :download, id: quotation_request 

     #verification 
     expect(@controller).to receive(:send_data).with(file_options) {@controller.render nothing: true}  
    end 
    end 
end 

控制器:

def download 
    @quotation_request = QuotationRequest.find(params[:id]) 
    send_data @quotation_request.sample_text, { 
    filename: @quotation_request.sample_text_file, 
    type: "text/plain", 
    disposition: "attachment" 
    } 
end 

測試的輸出:

1) QuotationRequestsController GET download streams the sample text as a text file 
    Failure/Error: expect(@controller).to receive(:send_data).with(file_options) { 
    @controller.render nothing: true 
    }  
    (# <QuotationRequestsController:0x007ff35f926058>).send_data({ 
    :filename=>"1-peter-johnson.txt", 
    :type=>"plain/text", 
    :disposition=>"attachment" 
    }) 
    expected: 1 time with arguments: ({ 
    :filename=>"1-peter-johnson.txt", 
    :type=>"plain/text", :disposition=>"attachment" 
    }) 
    received: 0 times 
    # ./spec/controllers/quotation_requests_controller_spec.rb:380:in `block (3 levels) in <top (required)>' 
    # -e:1:in `<main>' 
+0

我假設你正在使用'FactoryGirl.create'。你檢查過create(:quotation_request)是否成功創建記錄? – fylooi

+0

是的,我爲此測試。它創建quotation_request。 – chell

+0

您是否使用pry或調試器來調試測試用例? –

回答

3
#exercise 
    get :download, id: quotation_request 

    #verification 
    expect(@controller).to receive(:send_data).with(file_options) {@controller.render nothing: true}  

這是向後。期望應該在方法調用之前。

+0

我扭轉了上述兩行,我仍然得到相同的錯誤。有任何想法嗎 ?我應該如何寫這個測試? – chell

+0

這應該是解決方案,除非您的控制器操作未成功完成。 – fylooi

+0

控制器操作正在成功完成,因爲我可以在瀏覽器中對其進行測試。 – chell

4

你應該通過2個參數 expect(@controller).to receive(:send_data).with(quotation_request.sample_text, file_options) {@controller.render nothing: true}

1

你寫如下:

  1. 獲取文件
  2. 模擬文件

但正確的情況下反轉:

  1. 模擬文件
  2. 獲取文件

試試以下(使用before):

require 'rails_helper' 

RSpec.describe QuotationRequestsController, type: :controller do 
    describe "GET download" do 
    let(:quotation_request) { create(:quotation_request) } 
    let(:file_options) { {filename: "#{quotation_request.id}-#{quotation_request.client.name.parameterize}.txt", type: 'plain/text', disposition: 'attachment'} } 

    before do 
     expect(@controller).to receive(:send_data) 
     .with(file_options) { @controller.render nothing: true } 
    end 

    it "streams the sample text as a text file" do 
     get :download, id: quotation_request 
    end 
    end 
end