【问题标题】:Rspec Stubbing Object.map()Rspec 存根 Object.map()
【发布时间】:2015-01-19 01:09:18
【问题描述】:

在我的 Rails 控制器中,我正在尝试为方法 search_backups 编写测试。我遇到的问题是devices_ids_from_elastic = ConfigTextSearch.search search_term 什么都不返回,因此测试在devices_ids_from_elastic 上运行.map,这不正确是#<String:0x007f8a90b67ca0>

如何删除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)>'

测试:

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

控制器:

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

【问题讨论】:

  • 为什么不存根 ConfigTextSearch.search 并让它返回一个空数组或所需对象的数组?
  • 为什么reports.stub(ConfigTextSearch.search).with("sss").and_return(["help"]) 给我ArgumentError: wrong number of arguments (0 for 1..2)

标签: ruby-on-rails ruby-on-rails-3 unit-testing rspec


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 2014-09-15
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多