3

我有一个可以保存用户提交的链接的网站。create 操作接受一个 url,并从 html 中的 og:tags 中提取数据。该应用程序本身运行良好,但我无法使用 VCR 在 RSpec 中对其进行测试。

在没有 VCR 的情况下测试通过,但需要很长时间(实际代码有多个 HTTP 请求)。当我尝试使用 VCR 运行测试时,出现以下错误。我该如何解决这个问题?

Failure/Error: click_button 'submit'
VCR::Error::UnhandledHTTPRequestError:
   ================================================================================
   An HTTP request has been made that VCR does not know how to handle:
     GET http://espn.go.com/golf/masters13/story/_/id/9171606

链接控制器.rb

def create
  @link = Link.new(params[:link])
  if @link.save
    @link.title_from_url(@link.url)
  else
    render action: "new"
  end
end

链接.rb

def title_from_url(url)
  if !Nokogiri::HTML(open(url)).css("meta[property='og:title']").blank?
    self.title = Nokogiri::HTML(open(url)).css("meta[property='og:title']").first.attributes["content"].text
    self.save      
  end
end

link_pages_spec.rb

require 'spec_helper'

describe 'Link' do
  subject { page }
  before do
    visit root_path  
    click_link "create link"
  end
  describe "should be created with valid form" do
    VCR.use_cassette "link/create" do
      before do
        fill_in "enter url", with: "http://espn.go.com/golf/masters13/story/_/id/9171606"
        click_button "submit"
      end
      it { should have_selector('h2', text:'Adam Scott 1st Aussie to win Masters')}        
    end
  end
end

规范/支持/vcr_setup.rb

VCR.configure do |c|   
  c.cassette_library_dir = 'spec/vcr_cassettes'
  c.hook_into :fakeweb
end
4

1 回答 1

1

我有两件事错了。首先,需要Capybara.current_driver = :mechanize通过capybara-mechanizegem 设置我的。其次,需要在 it 块中包含 VCR 块(而不是描述)。所以下面的代码有效。

require 'spec_helper'

describe 'Link' do
  subject { page }
  it "should be created with valid form" do
    VCR.use_cassette "link/create" do
      Capybara.current_driver = :mechanize
      visit root_path  
      click_link "create link"
      fill_in "enter url", with: "http://espn.go.com/golf/masters13/story/_/id/9171606"
      click_button "submit"
      page.should have_selector('h2', text:'Adam Scott 1st Aussie to win Masters')        
    end
  end
end
于 2013-05-11T14:38:32.793 回答