如何在规范中存根Nokogiri

时间:2015-09-29 07:06:37

标签: ruby ruby-on-rails-3 rspec nokogiri

如何在RSpec的PromoDate的获取方法中存根Nokogiri

PlayerEndpoint

4 个答案:

答案 0 :(得分:1)

在这里你不仅应该存根Nokogiri :: HTML而且还应该使用“open”方法,所以你可以这样做:

expect(PromoDate).to receive(:open).and_return(File.new("#{Rails.root}/spec/fixtures/page_for_parsing.html"))
expect(Nokogiri::HTML::Document).to receive(:parse).and_return(whatever_you_want)

其中page_for_parsing.html是在fixtures文件夹中创建的html页面,用于测试目的。 Nokogiri :: HTML只是Nokogiri的一种便捷方法:: HTML :: Document.parse,你可以在source code中看到它

答案 1 :(得分:0)

看起来你需要比Nokogiri本身更多的OpenURI。

您可以使用Mocha gem轻松完成。

fake_html = <<-EOS
  <html>
    <head><title>Some Title</title></head>
    <body>Some Content</body>
  </html>
EOS
PromoDate.any_instance.stubs(:open).returns(fake_html)

您还可以在该测试中确保使用正确的参数调用此函数:

PromoDate.any_instance.expects(:open).with('http://www.google.com').returns(fake_html)

答案 2 :(得分:0)

allow(Nokogiri::HTML::Document).to \
receive(:parse).with(open("#{request.host}#{url}").body, \
nil, nil, Nokogiri::XML::ParseOptions::DEFAULT_HTML\
).and_return(your_fakeresponse_body)

归功于@ kaleb4eg,以确定正确的方法类和方法。

答案 3 :(得分:0)

PromoDate.send(:define_method, :open) { |*args| "" }
allow(promoDateobj::Nokogiri).to receive(:XML).with(anything).and_return(whatever_you_want)

尝试一下。我已经应用了它,对我来说很好用。