Add have_title RSpec matcher

This commit is contained in:
Jonas Nicklas 2013-02-16 10:02:32 +01:00
parent 6e488b6a8d
commit 8340e11610
2 changed files with 83 additions and 19 deletions

View File

@ -1,6 +1,16 @@
module Capybara
module RSpecMatchers
class HaveSelector
class Matcher
def wrap(actual)
if actual.respond_to?("has_selector?")
actual
else
Capybara.string(actual.to_s)
end
end
end
class HaveSelector < Matcher
def initialize(*args)
@args = args
end
@ -17,20 +27,12 @@ module Capybara
"have #{query.description}"
end
def wrap(actual)
if actual.respond_to?("has_selector?")
actual
else
Capybara.string(actual.to_s)
end
end
def query
@query ||= Capybara::Query.new(*@args)
end
end
class HaveText
class HaveText < Matcher
attr_reader :text
def initialize(text)
@ -59,20 +61,42 @@ module Capybara
"have text #{format(text)}"
end
def wrap(actual)
if actual.respond_to?("has_selector?")
actual
else
Capybara.string(actual.to_s)
end
end
def format(text)
text = Capybara::Helpers.normalize_whitespace(text) unless text.is_a? Regexp
text.inspect
end
end
class HaveTitle < Matcher
attr_reader :title
def initialize(title)
@title = title
end
def matches?(actual)
@actual = wrap(actual)
@actual.has_title?(title)
end
def does_not_match?(actual)
@actual = wrap(actual)
@actual.has_no_title?(title)
end
def failure_message_for_should
"expected there to be title #{title.inspect} in #{@actual.title.inspect}"
end
def failure_message_for_should_not
"expected there not to be title #{title.inspect} in #{@actual.title.inspect}"
end
def description
"have title #{title.inspect}"
end
end
def have_selector(*args)
HaveSelector.new(*args)
end
@ -81,7 +105,7 @@ module Capybara
HaveSelector.new(:xpath, xpath, options)
end
def have_css(css, options={})
def have_css(css, options={})
HaveSelector.new(:css, css, options)
end
@ -93,6 +117,10 @@ module Capybara
HaveText.new(text)
end
def have_title(title)
HaveTitle.new(title)
end
def have_link(locator, options={})
HaveSelector.new(:link, locator, options)
end

View File

@ -412,6 +412,42 @@ describe Capybara::RSpecMatchers do
end
end
describe "have_title matcher" do
it "gives proper description" do
have_title('Just a title').description.should == "have title \"Just a title\""
end
context "on a string" do
let(:html) { '<title>Just a title</title>' }
it "passes if there is such a title" do
html.should have_title('Just a title')
end
it "fails if there is no such title" do
expect do
html.should have_title('No such title')
end.to raise_error(/expected there to be title "No such title"/)
end
end
context "on a page or node" do
before do
visit('/with_js')
end
it "passes if there is such a title" do
page.should have_title('with_js')
end
it "fails if there is no such title" do
expect do
page.should have_title('No such title')
end.to raise_error(/expected there to be title "No such title"/)
end
end
end
describe "have_button matcher" do
let(:html) { '<button>A button</button><input type="submit" value="Another button"/>' }