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.

366 CHAPTER 13 Designing an API<br />

To get started with this show action, you’ll write a test in spec/api/v1/<br />

projects_spec.rb for it inside the “projects viewable by this user” context block, as<br />

shown in the following listing.<br />

Listing 13.13 spec/api/v1/projects_spec.rb<br />

context "show" do<br />

let(:url) { "/api/v1/projects/#{@project.id}"}<br />

before do<br />

Factory(:ticket, :project => @project)<br />

end<br />

it "JSON" do<br />

get "#{url}.json", :token => token<br />

project = @project.to_json(:methods => "last_ticket")<br />

last_response.body.should eql(project)<br />

last_response.status.should eql(200)<br />

project_response = JSON.parse(last_response.body)["project"]<br />

ticket_title = project_response["last_ticket"]["ticket"]["title"]<br />

ticket_title.should_not be_blank<br />

end<br />

end<br />

You’re using the project method that was set up by the “projects viewable by this<br />

user” context block earlier to generate the URL to a Project resource, as well as using<br />

it to create a new ticket for this project so that last_ticket returns something of<br />

value. You take this URL and do a JSON request on it, and you expect to get back a<br />

JSON representation of the object with the last_ticket method being called and also<br />

returning data. Then you check that the response’s status should be 200, indicating a<br />

good request, and finally you check that the last ticket title isn’t blank.<br />

To make this test pass, open app/controllers/api/v1/projects_controller.rb and add<br />

in the show action, as shown in the following listing.<br />

Listing 13.14 app/controllers/api/v1/projects_controller.rb<br />

def show<br />

@project = Project.find(params[:id])<br />

respond_with(@project, :methods => "last_ticket")<br />

end<br />

In this action, you find the Project based on the params[:id] value and then<br />

respond_with this object, asking it to call the last_ticket method. If this method is<br />

undefined (as it is right now), then the method will not be called at all. When you run<br />

this test with bin/rspec spec/api/v1/projects_spec.rb, you’ll see this error:<br />

Failure/Error: ticket_title = last_response ...<br />

You have a nil object when you didn't expect it!<br />

You might have expected an instance of Array.<br />

The error occurred while evaluating nil.[]

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

Saved successfully!

Ooh no, something went wrong!