简体   繁体   English

Rspec存根Object.map()

[英]Rspec Stubbing Object.map()

In my rails controller, I am trying to write a test for the method search_backups . 在我的rails控制器中,我正在尝试为search_backups方法编写测试。 The issue I am having is that devices_ids_from_elastic = ConfigTextSearch.search search_term returns nothing and so the test runs .map on devices_ids_from_elastic which is incorrectly a #<String:0x007f8a90b67ca0> . 我遇到的问题是devices_ids_from_elastic = ConfigTextSearch.search search_term返回任何内容,因此测试在devices_ids_from_elastic上运行.map ,该devices_ids_from_elastic错误地是#<String:0x007f8a90b67ca0>

How can I stub out devices_ids_from_elastic.map() to fix this issue? 如何存根devices_ids_from_elastic.map()来解决此问题?

Failures:

  1) ReportsController access control allows architects to search backups
     Failure/Error: post 'search_backups'
     NoMethodError:
       undefined method `each_pair' for #<String:0x007f8a90b67ca0>
     # ./app/controllers/reports_controller.rb:19:in `map'
     # ./app/controllers/reports_controller.rb:19:in `elastic_mongo_lookup'
     # ./app/controllers/reports_controller.rb:32:in `search_backups'
     # ./spec/controllers/reports_controller_spec.rb:123:in `block (3 levels) in <top (required)>'

test: 测试:

describe "controller method test" do
    before do
      allow(CSV).to receive(:generate).and_return("1234, blah")
      stub_request(:get, "http://localhost:9200/mongo_index/config_files/_search?q=").
        with(:headers => {'Expect'=>'', 'User-Agent'=>'Faraday v0.9.1'}).
        to_return(:status => 200, :body => '{lots of json stuff in here }', :headers => {})


    it "allows users to search backup log files" do
      reports = double(ReportsController)
      reports.stub(:map).and_return("help")
      post 'search_backups'
    end

controller: 控制器:

search_backups
     def elastic_mongo_lookup(search_term)
        devices_ids_from_elastic = ConfigTextSearch.search search_term
        device_ids = devices_ids_from_elastic.map { |device| device._source.device_id }
        csv_string = CSV.generate do |csv|
          Device.where(:_id.in => device_ids).each do |device|
            csv << [device.logical_name, device.primary_ip]
          end
        end
        return csv_string
      end

  def search_backups
    authorize! :read, :custom_report
    csv_string = elastic_mongo_lookup params[:search_term]
    if csv_string.blank?
      flash[:notice] = "No results were found"
      redirect_to reports_path
    else 
      render text: "DeviceID, primary_ip\n" + csv_string
    end
  end#search_backups

试试这个: allow(ConfigTextSearch).to receive(:search).with({}).and_return([])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM