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.

The projects API<br />

The before_save method here is run on a record whenever it is created or updated,<br />

as opposed to the before_create callback that you saw back in chapter 10, which only<br />

calls the specified method upon record creation.<br />

With the callback to create the token in place, let’s jump back to your spec and<br />

write a test to make a request with this token. Directly underneath the let(:user) in<br />

spec/api/v1/projects_spec.rb, you’ll put the code from the following listing.<br />

let(:token) { user.authentication_token }<br />

before do<br />

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

user.permissions.create!(:action => "view", :thing => @project)<br />

end<br />

context "projects viewable by this user" do<br />

let(:url) { "/api/v1/projects" }<br />

it "json" do<br />

get "#{url}.json"<br />

projects_json = Project.for(user).all.to_json<br />

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

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

projects = JSON.parse(last_response.body)<br />

projects.any? do |p|<br />

p["project"]["name"] == "Ticketee"<br />

end.should be_true<br />

end<br />

end<br />

You’re using another let to define a token method that, when called, will return the<br />

authentication_token for the current user. You’ll use this later for authenticating<br />

requests for your API. The get method B you use here is provided by<br />

Rack::Test::Methods and simply makes a GET request with the provided URL. You<br />

put the URL in a let because you don’t want to repeat the URL too many times if you<br />

have multiple tests, and the let stops you from repeating yourself in your code.<br />

After the request is done in the test, you ensure that the last_response.status<br />

returns 200, which is the HTTP status code for OK and means the request was successful.<br />

The rest of this spec tests that the data contained within last_response.body contains<br />

the appropriate data. This to_json method will take the attributes for each<br />

project returned and turn them into JSON, resulting in an output such as<br />

[<br />

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

{"project":<br />

{<br />

"created_at":"[timestamp]",<br />

"id":1,<br />

"name":"Ticketee",<br />

"updated_at":"[timestamp]"<br />

}<br />

B GET request<br />

353

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

Saved successfully!

Ooh no, something went wrong!