How do you use the rspec have_selector method to validate XML?

I want to do some basic validation to ensure that the XML sitemap is created correctly, but have_selector does not seem to be able to detect the tags:

 require 'spec_helper' describe SitemapController do render_views before(:all) do # code to generate factory data # ... end # illustrating the problem it "should be able detect nodes that are definitely present" do get :index response.should have_selector('url') end end 

Every time I run the test, I get the following error:

 RSpec::Expectations::ExpectationNotMetError: expected css "url" to return something 

A site map is created, and when I debug the RSpec test and look at the response object, I can see the contents of the xml:

 ruby-1.9.2-p180 :001 > response.body => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n <url>\n <loc>http://test.host/panel ... 

My sitemap is created by the SitemapController, and the view is in views/sitemap/index.builder.xml .

Why don't you have not_selector?

+6
source share
3 answers

Capybara does not support XML responses. It always uses Nokogiri::HTML to parse the content, which gives unexpected results when providing XML.

The addition of XML support contained but was rejected by a supporter of Capybara.

+3
source

Use should have_xpath('//url') instead. have_selector for CSS.

See Capybara README for more details.

+2
source

As far as I can tell, have_selector (or have_xpath ) can only come from Webrat or Capybara. You are correct in your comment on John that you do not need a browser simulator to test the API.

You may mistakenly refer to Webrat or Capybara as they use visit instead of get AFAIK. Thus, the variables with which they are mapped could never be populated with a page and therefore will always return false.

Rails should process the XML document initially if the response content type is correctly set to XML. Try using the assert_tag or assert_content test helper as a basic check.

I would just use Nokogiri to parse XHTML and run regular RSpec tests against this:

 xml = Nokogiri::XML(response.body) xml.css("expression").size.should == 1 
+1
source

Source: https://habr.com/ru/post/902631/


All Articles