在rails中我正在使用search_backups
编写控制器方法Rspec
的测试:
def elastic_mongo_lookup(search_term)
devices_ids_from_elastic = ConfigTextSearch.search search_term
puts devices_ids_from_elastic
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
describe "try controller method" do
let(:reports_controller) { ReportsController.new }
before do
allow(CSV).to receive(:generate).and_return("1234", "blah")
allow(ConfigTextSearch).to receive(:search).and_return(['"hits": [ {"_source":{"device_id":"54afe167b3000006"}]'])
allow(:devices_ids_from_elastic).to receive(:map).and_return('54afe167b3000006')
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 => '', :headers => {})
end
it "allows people to search backups" do
reports = double(ReportsController)
post 'search_backups'
end
end
问题在于ConfigTextSearch.search search_term
会返回一个弹性搜索ORM对象..这意味着我无法将其存根,因为.map()
上的devices_ids_from_elastic.map
方法对其来说是唯一的&#39;嵌套_source
方法。
我怎样才能完全绕过elastic_mongo_lookup
而只是将模拟的csv_string
返回search_backups
?
答案 0 :(得分:1)
在RSpec控制器测试中,controller
被定义为被测控制器。因此,您可以通过以下方式实现您的要求:
allow(controller).to receive(:elastic_mongo_lookup).and_return('whatever string you choose')