I’m using RSpec in with Ruby on Rails. I’ve made a helper module
method that generates some HTML and would like to create a rspec test
to validate this HTML. I can of cause use regex to validate it as a
string, but would much rather validate it by traversing the DOM and
checking that the elements I expect is present. Any pointers?
On Oct 18, 2008, at 4:40 AM, Thomas W. Steen wrote:
Hi
I’m using RSpec in with Ruby on Rails. I’ve made a helper module
method that generates some HTML and would like to create a rspec
test to validate this HTML. I can of cause use regex to validate it
as a string, but would much rather validate it by traversing the DOM
and checking that the elements I expect is present. Any pointers?
No - that’s not really an option. The rails stack has no idea about a
DOM.
One option, though, is to stub methods and use message expectations.
For instance, if you had a helper like the following:
module MyHelper
def my_method(a_name)
link_to(a_name, {:controller => “foo”, :action => “foo”})
end
end
You’d be able to write a spec like the following:
it “should link with the correct name” do
helper.should_receive(:link_to).with(“foo”, {:controller =>
“foo”, :action => “foo”})
helper.my_method(“foo”)
end
No - that’s not really an option. The rails stack has no idea about a
DOM.
Hrm…he’s just generating HTML, he should be able to use Hpricot.
Does have_tag work with plain strings, or only in examples where there’s
a response body? If it’s the latter, we should make it work with plain
strings as well. But Hpricot would certainly be useful I would think.
You’d be able to write a spec like the following:
it “should link with the correct name” do
helper.should_receive(:link_to).with(“foo”, {:controller => “foo”,
:action => “foo”})
helper.my_method(“foo”)
end
I don’t like this, I don’t think you’re testing anything here.
Hi Pat. I’m interested to hear how you’d spec that helper method,
because some of specs are similar to what Scott proposed, and I’m
always looking to improve them.
I don’t like this, I don’t think you’re testing anything here.
Pat
Hi Pat. I’m interested to hear how you’d spec that helper method, because
some of specs are similar to what Scott proposed, and I’m always looking to
improve them.
I’m pretty sure Pat is simply suggesting:
it “should link with the correct name” do
helper.my_method(“foo”).should have_tag(“a[href=?]”, the_path,
“foo”)
end
If my_method returns a string then have_tag will work. If my_method
returns an object that responds to “body” then it will also work (this
is how response.should have_tag(‘…’) works as well,