27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

510 CHAPTER 17 Engines<br />

Listing 17.19 spec/integration/posts_spec.rb<br />

it "should see the post count and last post details" do<br />

visit topics_path<br />

within "#topics tbody td#posts_count" do<br />

page.should have_content("1")<br />

end<br />

within "#topics tbody td#last_post" do<br />

page.should have_content("last post was less than a minute ago<br />

➥by some_guy")<br />

end<br />

end<br />

This test ensures that the post count is showing the correct number of posts and that<br />

the last post details are displayed correctly. When you run this spec, it will pass the first<br />

assertion because of the posts count you set up a little earlier, 21 but it fails on the last<br />

assertion because it cannot find the content you’ve specified:<br />

Failure/Error: page.should have_content("[content]")<br />

expected #has_content?("[content]") to return true, got false<br />

The first part of your content is “last post was less than a minute ago.” Let’s focus on<br />

getting this working. There’s a helper within Rails that can help you display this “less<br />

than a minute ago” text called time_ago_in_words. Let’s assume that you’ve got a<br />

method called last_post that returns the last post for now. You’ll define it later. You<br />

can use the time_ago_in_words helper within the last post table cell in app/views/<br />

forem/topics/index.html.erb:<br />

<br />

last post was ago<br />

<br />

This time_ago_in_words helper will display a humanized version of how long ago the<br />

post was. When you first create the post, the text would read “less than a minute ago,”<br />

as this is the smallest granularity that this helper provides.<br />

Before your test will pass, you’re going to need the other half of this line. At the<br />

end of the %> on the line you just wrote, add this:<br />

by <br />

This first uses a new method that you’ll define shortly on the Forem::Topic model<br />

called last_post, which will return the last post for this topic. Then, you’ll display<br />

who posted that post by calling user on that object.<br />

When you run your test again, this time it will fail because the last_post method<br />

on topic is only defined in your imagination:<br />

ActionView::Template::Error:<br />

undefined method `last_post' for #<br />

21 Naughty of us not to write tests back then, but sometimes this happens.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!