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.

496 CHAPTER 17 Engines<br />

Note that the params[:topic_id] here doesn’t need to be namespaced yet again<br />

because you’re isolated. This feature is really saving you a lot of useless typing! Now,<br />

with the action defined in the controller, you’re going to need a view too. You’ll<br />

define it with a couple of lines in a new file at app/views/forem/posts/new.html.erb:<br />

New Post<br />

<br />

"form", :locals => { :post => post } %><br />

<br />

<br />

Always specify options when using locals<br />

If, in this example, you used this line to render the partial<br />

{ :post => post } %><br />

the :locals option would be ignored by render. You must always use the :partial<br />

option in conjunction with the :locals option; otherwise it will not work.<br />

With the code in the controller for the before_filter, the new action defined, and<br />

the view written, when you run your spec again with bin/rspec spec/integration/<br />

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

AbstractController::ActionNotFound:<br />

The action 'create' could not be found for Forem::PostsController<br />

You now need to define the create action within your Forem::PostsController:<br />

def create<br />

@post = @topic.posts.create(params[:post])<br />

flash[:notice] = "Post has been created!"<br />

redirect_to topic_path(@topic)<br />

end<br />

This action will create a new post for the topic with the non-namespaced parameters<br />

that have been passed in, set the flash[:notice], and send the user back to the<br />

topic_path(@topic) path. Hey, that’s about all that your test needs, isn’t it? Let’s find<br />

out with another run of bin/rspec spec/integration/posts_spec.rb:<br />

1 example, 0 failures<br />

Awesome! That was easy, wasn’t it? You’ve now got a way for users to post replies to<br />

topics for your engine in a couple of steps. You repeated a couple of the steps you performed<br />

in the last section, but it’s good to have this kind of repetition to enforce the<br />

concepts. Additionally, having topics without posts would be kind of silly.<br />

Before you run your specs, RSpec has generated controller tests incorrectly for<br />

your application, calling the classes inside the files at spec/controllers/forem/topics<br />

_controller_spec.rb and spec/controllers/forem/posts_controller_spec.rb Topics-<br />

Controller and PostsController, respectively. You will need to change these to

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

Saved successfully!

Ooh no, something went wrong!