You are viewing marnen

Marnen Laibow-Koser's Journal - A tip for Rails and RSpec [entries|archive|friends|userinfo]
Marnen Laibow-Koser

[ website | My Website ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

A tip for Rails and RSpec [Mar. 28th, 2008|02:26 pm]
Previous Entry Share Next Entry
[Tags|, , , ]

This probably won't be of interest to anyone who isn't a Ruby on Rails developer, but since it seems that the thing to do in the Rails community is share tips in blog posts, I thought I might as well jump on the bandwagon.

content_for is a great method to use in Rails views, but I found it hard to test in RSpec -- I couldn't mock the right object to test for the method call, and I couldn't figure out how to get the content variable out of the response. Then I stumbled on RSpec patch 12701, which was incorporated into RSpec releases some time ago (it's in 1.1.3, certainly, and I don't know how far back it goes). It seems that while response can be tested for the main body of the response, anything defined with content_for is available as if it were a hash element. So if your view looks like:

<% content_for :sidebar do %>
  <p>Here's my sidebar text.</p>
<% end %>

<p>And here's my main content.</p>
then you can write a spec that looks something like
describe "my view" do
  before(:each) do
    render 'myview'
  end

  it "should populate the body content" do
    response.should have_tag("p", /main content/)
  end

  it "should populate the sidebar" do
    response[:sidebar].should have_tag("p", /sidebar/)
  end
end
I just went through an hour or two of pain before stumbling on this, so I thought I'd save everyone else some trouble.

LinkReply

Comments:
[User Picture]From: zimarra
2008-03-28 09:48 pm (UTC)

(Link)

~I cast tongues to try to decipher what's this post about~

*FAILED*

*Eyes go glassy and goes back to sleep*

Hey Marnen, on a side note, you going to be around the weekend of 10 April? I'd like to chat with you at some point again. Maybe you could give me advice regarding my broken fiddle, among other things.. :)
[User Picture]From: marnen
2008-03-28 10:01 pm (UTC)

(Link)

Well, as you might have seen from the first paragraph, this is a tip regarding Ruby on Rails development.

I don't think I'll be around the weekend of 12 April (I'll probably be at Æthelmearc coronation, since I know the princess's father and have met the princess herself once or twice). But I'd be happy to talk about your fiddle some other time...
[User Picture]From: zimarra
2008-03-28 10:16 pm (UTC)

(Link)

Okays. :)

(Gods I've been hanging around a kobold too much. (no, not Konan, another kobold..)