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.

502 CHAPTER 17 Engines<br />

forem_user; if it can’t do that, it will create one instead. This will then be the object that<br />

is returned when you reference current_user in your application.<br />

The next function you’re going to add to your engine is one that will redirect users<br />

who aren’t logged in when they attempt to access the new action in Forem::Topics-<br />

Controller. Your test will also test that an unauthenticated user can’t see the New<br />

Topic link on theForem::TopicsController’s index action. You’ll add this spec in<br />

spec/integration/topics_spec.rb by using the code in the following listing.<br />

Listing 17.14 spec/integration/topics_spec.rb<br />

context "unauthenticated users" do<br />

before do<br />

sign_out!<br />

end<br />

it "cannot see the 'New Topic' link" do<br />

visit topics_path<br />

page.should_not have_content("New Topic")<br />

end<br />

it "cannot begin to create a new topic" do<br />

visit new_topic_path<br />

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

end<br />

end<br />

In the before block of this new context, you call the sign_out! method, which will<br />

set up the crucial current_user method that this test depends on. If it wasn’t defined,<br />

then you’d get an undefined method when current_user attempted to access it.<br />

In this spec, you use page.current_url B to read what the current URL is; it should<br />

match whatever main_app.sign_in_path’s method points at. Remember: this is the<br />

sign_in_path method, which is made available in the application by a definition in its<br />

config/routes.rb file. This is not currently set up, and so you’ll do that later.<br />

First, let’s see what the output has to say about your first test when you run bin/<br />

rspec spec/integration/topics_spec.rb:25:<br />

Failure/Error: page.should_not have_content("New Topic")<br />

expected #has_content?("New Topic") to return false, got true<br />

You’re asserting in your test that an unauthenticated user cannot see the New Topic<br />

link, but they do. You can go into app/views/forem/topics/index.html.erb and change<br />

this line<br />

<br />

to these lines:<br />

<br />

<br />

<br />

B Read current URL

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

Saved successfully!

Ooh no, something went wrong!