我有以下方法,它负责请求URL并返回它的Nokogiri::HTML文档。该方法检查是否定义了代理,如果定义了代理,它将使用或不使用代理选项调用OpenURI的open。
Implementation
require 'open-uri'
require 'nokogiri'
class MyClass 
  attr_accessor :proxy
  # ....
  def self.page_content(url)
    if MyClass.proxy
      proxy_uri = URI.parse(MyClass.proxy)
      Nokogiri::HTML(open(url, :proxy => proxy_uri)) # open provided by OpenURI
    else
      Nokogiri::HTML(open(url)) # open provided by OpenURI
    end
  end
end我不知道该如何编写能够证明以下内容的测试:
这是我作为测试的开始的想法。
describe MyClass, :vcr do
  describe '.proxy' do
    it { should respond_to(:proxy) }
  end
  describe '.page_content' do
    let(:url) { "https://google.com/" }
    let(:page_content) { subject.page_content(url) }
    it 'returns a Nokogiri::HTML::Document' do
      page_content.should be_a(Nokogiri::HTML::Document)
    end
    # How do i test this method actually uses a proxy when it's set vs not set?
    context 'when using a proxy' do
      # ???
      xit 'should set open-uri proxy properties' do
      end
    end
    context 'when not using a proxy' do
      # ???
      xit 'should not set open-uri proxy properties' do
      end
    end
  end
end发布于 2013-08-11 05:59:01
首先,您需要安排proxy方法在一个测试用例中返回代理,而不是在另一个测试用例中返回代理。如果有一个用于代理的"setter“方法,您可以使用它,否则可以对proxy方法进行存根。
然后,至少要对open设置一个期望,即它将被调用,这取决于它是哪种测试,是否带有:proxy选项。除此之外,您还可以选择是否对该方法中涉及的其他各种调用(包括URI.parse和Nokogiri::HTML )进行存根和设置期望。
有关建立双倍测试和设置期望的信息,请参见https://github.com/rspec/rspec-mocks。特别要注意的是,如果您想要使用部分固执方法,请使用and_call_original选项。
更新:这里有一些代码可以让您开始工作。这适用于非代理方法。我已经把代理案件留给你了。还请注意,这使用了“部分固执”方法,在这种方法中,您仍然会调用外部gems。
require 'spec_helper'
describe MyClass do
  describe '.proxy' do         # NOTE: This test succeeds because of attr_accessor, but you're calling a MyClass.proxy (a class method) within your page_content method
    it { should respond_to(:proxy) }
  end
  describe '.page_content' do
    let(:url) { "https://google.com/" }
    let(:page_content) { MyClass.page_content(url) } # NOTE: Changed to invoke class method
    context 'when not using a proxy' do
      before {allow(MyClass).to receive(:proxy).and_return(false)} # Stubbed for no-proxy case
      it 'returns a Nokogiri::HTML::Document' do
        page_content.should be_a(Nokogiri::HTML::Document)
      end
      it 'should not set open-uri proxy properties' do
        expect(MyClass).to receive(:open).with(url).and_call_original  # Stubbing open is tricky, see note afterwards
        page_content
      end
    end
        # How do i test this method actually uses a proxy when it's set vs not set?
    context 'when using a proxy' do
      # ???
      xit 'should set open-uri proxy properties' do
      end
    end
  end
endopen的顽固性是很棘手的。有关解释,请参见How to rspec mock open-uri?。
https://stackoverflow.com/questions/18168569
复制相似问题