27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Classes outside your control<br />

This includes Forem::TopicsController, where you just used it, and Forem::Posts-<br />

Controller, where you are about to use it to ensure that users are signed in before<br />

being able to create new posts.<br />

Before you use this method, you’ll add a test to the spec/integration/posts_spec.rb<br />

to check that a user cannot access the new action if they aren’t signed in, and it will fail<br />

because you’re not using it yet.<br />

You’re going to have two context blocks in your spec, one for unauthenticated<br />

users and the other for authenticated users. You can share the before block between<br />

these two contexts if you take the sign_in! method out and turn your spec into what’s<br />

shown in the following listing.<br />

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

require 'spec_helper'<br />

describe "posts" do<br />

before do<br />

@topic = Forem::Topic.new(:subject => "First topic!")<br />

@topic.posts.build(:text => "First post!")<br />

@topic.save!<br />

end<br />

context "unauthenticated users" do<br />

before do<br />

sign_out!<br />

end<br />

end<br />

context "authenticated users" do<br />

before do<br />

sign_in!<br />

end<br />

it "reply to a topic" do<br />

...<br />

end<br />

end<br />

end<br />

With the before block now run before both of your contexts, you’ll have the @topic<br />

object available in both of them. In the “unauthenticated users” context block, you’ll<br />

write your test for the unauthenticated new action access under the before block,<br />

using the code from the following listing.<br />

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

it "cannot access the new action" do<br />

visit new_topic_post_path(@topic)<br />

page.current_url.should eql(sign_in_url)<br />

end<br />

507

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

Saved successfully!

Ooh no, something went wrong!