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 />

Next, you’ll apply what you’ve done here to associate the users who are signed in<br />

with the topics they post. This is so people will be able to see who posted what.<br />

17.7.3 Authenticating topics<br />

By having a belongs_to :user association on the Forem::Post and Forem::Topic<br />

models, you’ll be able to assign users to topics and posts when they create them so that<br />

other users can know who’s been posting what.<br />

You’ve got, on purpose, no authentication in your dummy application at the<br />

moment, and so you’ll have to take a shortcut around this. Usually an application<br />

would provide a current_user method that returns a User object, but your dummy<br />

application doesn’t do this right now. You need this method to sometimes return a user<br />

object (like with actions that require authentication), and to sometimes return nil.<br />

A cool way to do this would be to dynamically redefine the current_user method<br />

yourself. A way to do this is to have two methods that you can call in your tests—a<br />

sign_in! method and a sign_out! method—which will redefine the current_user<br />

method in ApplicationController to either return the user object or nil, respectively.<br />

You’ll also make this method a helper method by using the helper_method<br />

method, which is available in all controllers. This will mean that your fake<br />

current_user method can then be referenced by the controllers and views of your<br />

engine without any problems.<br />

Define these two new methods in a new file at spec/support/dummy_login.rb using<br />

the code shown in the following listing.<br />

Listing 17.13 spec/support/dummy_login.rb<br />

def sign_out!<br />

ApplicationController.class_eval

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

Saved successfully!

Ooh no, something went wrong!