croceldon
croceldon

Reputation: 4595

How to test file download with Rails, Paperclip and RSpec request spec?

I have a request spec that is trying to test file download functionality in Rails 3.1 for me. The spec (in part) looks like this:

get document_path(Document.first)
logger(response.body)
response.should be_success

It fails with:

Failure/Error: response.should be_success
       expected success? to return true, got false

But if I test the download in the browser, it downloads the file correctly.

Here's the action in the controller:

def show
  send_file @document.file.path, :filename => @document.file_file_name,
                                 :content_type => @document.file_content_type
end

And my logger gives this information about the response:

<html><body>You are being <a href="http://www.example.com/">redirected</a>.</body></html>

How can I get this test to pass?

Update:

As several pointed out, one of my before_filters was doing the redirect. The reason is that I was using Capybara to login in the test, but not using it's methods for navigating around the site. Here's what worked (partially):

click_link 'Libraries'
click_link 'Drawings'
click_link 'GS2 Drawing'
page.response.should be_success #this still fails

But now I can't figure out a way to test the actual response was successful. What am I doing wrong here.

Upvotes: 1

Views: 3406

Answers (2)

fearless_fool
fearless_fool

Reputation: 35159

I was getting the same redirect until I realized that my login(user) method was the culprit. Cribbed from this SO link, I changed my login method to:

# file: spec/authentication_helpers.rb
module AuthenticationHelpers
  def login(user)
    post_via_redirect user_session_path, 'user[email]' => user.email, 'user[password]' => user.password
  end
end

In my tests:

# spec/requests/my_model_spec.rb
require 'spec_helper'
require 'authentication_helpers'

describe MyModel do
  include AuthenticationHelpers
  before(:each) do
    @user = User.create!(:email => '[email protected]', :password => 'password', :password_confirmation => 'password')
    login(@user)
  end

  it 'should run your integration tests' do
    # your code here
  end
end

[FWIW: I'm using Rails 3.0, Devise, CanCan and Webrat]

Upvotes: 0

rlkw1024
rlkw1024

Reputation: 6515

Most likely, redirect_to is being called when you run your test. Here's what I would do to determine the cause.

  1. Add logging to any before filters that could possibly run for this action.
  2. Add logging at several points in the action itself.

This will tell you how far execution gets before the redirect. Which in turn will tell you what block of code (probably a before_filter) is redirecting.

If I had to take a guess off the top of my head, I'd say you have a before_filter that checks if the user is logged in. If that's true, then you'll need to make sure your tests create a logged-in session before you call the login-protected action.

Upvotes: 1

Related Questions