Rspec Stubbing Object.map()

时间:2015-01-19 01:09:18

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

在我的rails控制器中,我正在尝试为方法search_backups编写测试。我遇到的问题是devices_ids_from_elastic = ConfigTextSearch.search search_term没有返回任何内容,因此.map上的devices_ids_from_elastic运行#<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

控制器:

{{1}}

1 个答案:

答案 0 :(得分:1)

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