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.

Adding more posts to topics<br />

Let’s start with running this test using bin/rspec spec/integration/<br />

posts_spec.rb. It will get through the first two steps, but fail because it cannot find a<br />

Reply link:<br />

Capybara::ElementNotFound:<br />

no link with title, id or text 'Reply' found<br />

This link needs to go in the app/views/forem/posts/_post.html.erb, and you can do<br />

that by using this text and placing it inside the div_for in the file, as that’s where your<br />

test is expecting the link to be:<br />

<br />

This Reply link will go to the new action within the Forem::PostsController. The<br />

nested route helper that you use, new_topic_post_path, will again reference only the<br />

engine’s new_topic_post_path because the engine is isolated. To define this route<br />

helper and the relevant routes for it, you’ll open config/routes.rb and alter this line<br />

resources :topics<br />

to now be these lines:<br />

resources :topics do<br />

resources :posts<br />

end<br />

When you re-run your spec, you get this error:<br />

ActionController::RoutingError:<br />

uninitialized constant Forem::PostsController<br />

You need to generate this controller, which you can do by running this command:<br />

rails g controller posts<br />

Again, this will generate a namespaced controller because you’ve isolated your<br />

engine. In this controller, you’re going to need to define a new action, as well as a<br />

before_filter to load the topic. You’ll change your Forem::PostsController into<br />

what’s shown in the following listing.<br />

Listing 17.11 app/controllers/forem/posts_controller.rb<br />

module Forem<br />

class PostsController < ApplicationController<br />

before_filter :find_topic<br />

def new<br />

@post = @topic.posts.build<br />

end<br />

private<br />

def find_topic<br />

@topic = Forem::Topic.find(params[:topic_id])<br />

end<br />

end<br />

end<br />

495

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

Saved successfully!

Ooh no, something went wrong!