Rspec send_data测试未通过

时间:2016-09-16 04:55:56

标签: ruby-on-rails rspec

我似乎无法通过此测试,但我不明白为什么。

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>'

4 个答案:

答案 0 :(得分:4)

你应该传递2个参数 expect(@controller).to receive(:send_data).with(quotation_request.sample_text, file_options) {@controller.render nothing: true}

答案 1 :(得分:3)

  #exercise
  get :download, id: quotation_request

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

这是倒退的。期望应该在方法调用之前。

答案 2 :(得分:1)

您写下以下内容:

  1. 获取档案
  2. 模拟文件
  3. 但正确的情况是倒置的:

    1. 模拟文件
    2. 获取档案
    3. 尝试关注(使用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
      

答案 3 :(得分:0)

Rails 5:

expect(@controller).to receive(:send_data).with(quotation_request.sample_text, file_options) {@controller.head :ok}

参考:https://stackoverflow.com/a/43428992