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.

228 CHAPTER 9 File uploading<br />

sign_in(:user, good_user)<br />

end<br />

it "can access assets in a project" do<br />

get 'show', :id => asset.id<br />

response.body.should eql(File.read(path))<br />

end<br />

end<br />

If you’re using Windows you may have to do this on the response.body line instead,<br />

because the line breaks on Windows are slightly different:<br />

response.body.gsub!(/\r\n?/, "\n").should eql(File.read(path))<br />

In this example, you sign in as the good_user by using another before block. Then<br />

you assert that when this user attempts to get this asset through the show action, the<br />

user should receive it as a response. Write another context and spec for the bad_user<br />

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

Listing 9.10 spec/controllers/assets_controller_spec.rb<br />

context "users without access" do<br />

before do<br />

sign_in(:user, bad_user)<br />

end<br />

it "cannot access assets in this project" do<br />

get 'show', :id => asset.id<br />

response.should redirect_to(root_path)<br />

flash[:alert].should eql("The asset you were looking for<br />

➥could not be found.")<br />

end<br />

end<br />

Here you sign in as the bad_user and then deny all knowledge of the asset’s existence<br />

by redirecting to root and displaying an alert flash message. Let’s run these specs now<br />

with bin/rspec spec/controllers/assets_controller_spec.rb. Both examples<br />

complain:<br />

The action 'show' could not be found for FilesController<br />

Well, that’s no good. Now you need to define this show action.<br />

9.3.2 Showing your assets<br />

Open your FilesController file and define the show action, along with a<br />

before_filter to set the current_user variable, which you’ll need for permission<br />

checking. This code is shown in the following listing.<br />

Listing 9.11 app/controllers/files_controller.rb<br />

class FilesController < ApplicationController<br />

before_filter :authenticate_user!<br />

def show

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

Saved successfully!

Ooh no, something went wrong!