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.

378 CHAPTER 13 Designing an API<br />

You can run these two commands to run this migration, and then you’ll be on your<br />

way:<br />

rake db:migrate<br />

rake db:test:prepare<br />

You can now write a test to make sure that the request count is going to be incremented<br />

with each request. You’ll open a new file at spec/v1/api/rate_limit_spec.rb so that you<br />

can separate these tests from the others, because they are not part of the projects API<br />

or the errors from it. Into this file you’ll put the code from the following listing.<br />

Listing 13.25 spec/v1/api/rate_limit_spec.rb<br />

require 'spec_helper'<br />

describe "rate limiting", :type => :api do<br />

let(:user) { create_user! }<br />

it "counts the user's requests" do<br />

user.request_count.should eql(0)<br />

get '/api/v1/projects.json', :token => user.authentication_token<br />

user.reload<br />

user.request_count.should eql(1)<br />

end<br />

end<br />

When you run this spec now with bin/rspec spec/v1/api/rate_limit_spec.rb, it’s<br />

going to fail on the final line because the request count hasn’t been incremented:<br />

Failure/Error: user.request_count.should eql(1)<br />

expected 1<br />

got 0<br />

(compared using eql?)<br />

Alright, now that you’ve got a failing test, you can make it work! Open app/<br />

controllers/api/v1/base_controller.rb and add in a new method called check_rate<br />

_limit right underneath the current_user method, using this code:<br />

def check_rate_limit<br />

@current_user.increment!(:request_count)<br />

end<br />

By calling the increment! method on the user object, the field specified will be incremented<br />

once. To call this method, you’ll put it as another before_filter underneath<br />

the authenticate_user one at the top of this controller:<br />

before_filter :check_rate_limit<br />

That’s all there is to it, and so it will pass when you run bin/rspec spec/api/v1/<br />

rate_limit_spec.rb:<br />

1 example, 0 failures<br />

This is splendid. Before you run any more specs or make any commits, you’ll do what<br />

you came here to do: limit some rates.

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

Saved successfully!

Ooh no, something went wrong!