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.

Classes outside your control<br />

When you run this example again with bin/rspec spec/integration/topics_spec<br />

.rb:25, you’ll see that it now passes:<br />

1 example, 0 failures<br />

One down, two to go. Let’s run the next spec down in this file with bin/rspec spec/<br />

integration/topics_spec.rb:30. When you do, you’ll see this output:<br />

NoMethodError:<br />

undefined local variable or method `sign_in_url' for ...<br />

Your test currently can’t find the sign_in_path helper for your dummy application.<br />

You can define the helper by putting this line in spec/dummy/config/routes.rb:<br />

match "/sign_in", :to => "fake#sign_in", :as => "sign_in"<br />

When you run your test again with bin/rspec spec/integration/topics_spec<br />

.rb:30, you’ll be shown this:<br />

expected "http://www.example.com/login"<br />

got "http://www.example.com/forem/topics/new"<br />

The page expected to be on /login, but was actually on /forem/topics/new! That’s<br />

because you’re not yet authenticating users when they go to the new action in<br />

Forem::TopicsController. You can add a before_filter to the class definition in<br />

app/controllers/forem/topics_controller.rb using this code:<br />

before_filter :authenticate_forem_user!, :only => [:new, :create]<br />

You’ll put this authenticate_forem_user! method definition inside Forem<br />

::ApplicationController so that you can use it for all the controllers of your engine.<br />

It’ll go like this:<br />

private<br />

def authenticate_forem_user!<br />

if !current_user<br />

flash[:notice] = "You must be authenticated before you can do that."<br />

redirect_to main_app.sign_in_url<br />

end<br />

B Go to login path<br />

end<br />

Now when you visit your new or create actions in Forem::TopicsController, you’ll<br />

be sent away to the login path for your application, which you can access by calling<br />

sign_in_path on the main_app helper B. You must use main_app here so that you<br />

point to the application’s routes rather than the engine’s. The engine itself has no<br />

concept of sign_in_path.<br />

When you run your spec again with bin/rspec spec/integration/topics_spec<br />

.rb:30, you’ll see that this test is now failing because your application is missing the<br />

FakeController that your sign_in_path route uses:<br />

ActionController::RoutingError:<br />

uninitialized constant FakeController<br />

503

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

Saved successfully!

Ooh no, something went wrong!