我有一个可以保存用户提交的链接的网站。 create动作接受一个url,并从html中的og:标签中提取数据。该应用程序本身工作正常,但我在使用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
links_controller.rb
def create
@link = Link.new(params[:link])
if @link.save
@link.title_from_url(@link.url)
else
render action: "new"
end
end
Link.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
答案 0 :(得分:1)
我有两件事是错的。首先,需要通过Capybara.current_driver = :mechanize
gem设置capybara-mechanize
。其次,需要将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