Skip to content

Instantly share code, notes, and snippets.

@foca
Created August 5, 2008 06:24
Show Gist options
  • Save foca/4035 to your computer and use it in GitHub Desktop.
Save foca/4035 to your computer and use it in GitHub Desktop.
# this uses RspecHpricotMatchers: http://github.com/pd/rspec_hpricot_matchers
module FormFieldHpricotMatchers
# TODO: Add support for selects
# TODO: Test with anything that isn't an input[type=text] :P
class HaveField
include RspecHpricotMatchers
def initialize(id, type, tagname)
@tagname = tagname
@type = type
@id = id
@tag_matcher = have_tag("#{@tagname}##{@id}", @tagname == "textarea" ? @value : nil)
end
def named(name)
@name_set = true
@name = name
self
end
def with_label(label)
@label_set = true
@label = label
self
end
def with_value(value)
@value_set = true
@value = value
self
end
def matches?(actual)
@label ? have_tag("label[@for=#{@id}]", @label).matches?(actual) : true
@tag_matcher.matches?(actual) do |field|
field["type"].should == @type if @type
field["name"].should == @name if @name_set
field["value"].should == @value if @value_set && @tagname == "input"
end
end
def failure_message
attrs = [
"id ##{@id}",
@name && "name '#{@name}'",
@type && "type '#{@type}'",
@label && "labelled '#{@label}'",
@value && "value '#{@value}'"
].compact.join(", ")
"You expected a #{@tagname}#{@type ? " (#{@type})" : ""} with #{attrs} but found none.\n\n#{@tag_matcher.failure_message}"
end
end
def have_field(id, type="text", tagname="input")
HaveField.new(id, type, tagname)
end
def have_textfield(id)
have_field(id)
end
def have_password(id)
have_field(id, "password")
end
def have_checkbox(id)
have_field(id, "checkbox")
end
def have_checkbox(id)
have_field(id, "checkbox")
end
def have_textarea(id)
have_field(id, nil, "textarea")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment