2012-01-05 62 views
0

我有一個請求規範,試圖在我的Rails 3.1中測試文件下載功能。該規範(部分)如下:如何使用Rails,Paperclip和RSpec請求規範測試文件下載?

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

它失敗:

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

但是,如果我在瀏覽器中測試下載,它正確地下載文件。

這裏是在控制器中的作用:

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

我的記錄器提供了有關回應此信息:

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

我怎樣才能得到這個測試通過?

更新:

正如一些人士指出,我before_filters的人做重定向。原因是我使用Capybara登錄測試,但沒有使用它的方法來瀏覽網站。這是什麼工作(部分):

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

但現在我想不出一種方法來測試實際的響應是成功的。我在這裏做錯了什麼。

+1

聲音對我喜歡之前的過濾器(例如,檢查用戶登錄的過濾器)在動作運行之前重定向。 – 2012-01-05 19:29:01

+0

你真的很棒。不過,我仍然無法測試迴應。 – croceldon 2012-01-05 19:59:38

+0

@croceldon:讓我知道下面的登錄方法(在AuthenticationHelpers中)是否有所作爲 - 我很想知道它是否是同樣的問題。 – 2012-01-11 19:34:41

回答

1

最有可能的是,當您運行測試時會調用redirect_to。以下是我將如何確定原因。

  1. 將日誌記錄添加到可能運行此操作的任何過濾器之前。
  2. 在動作本身的多個點添加日誌記錄。

這會告訴你在重定向之前執行得有多遠。這反過來會告訴你哪些代碼塊(可能是before_filter)正在重定向。

如果我不得不猜測我的頭頂,我會說你有一個before_filter,檢查用戶是否登錄。如果這是真的,那麼你需要確保你的測試創建在您調用受登錄保護的操作之前登錄的會話。

+0

我的測試確實爲用戶創建了登錄會話,所以我不確定這可能是什麼問題。我會通過嘗試你提到的日誌來看看我能找到什麼。 – croceldon 2012-01-05 19:40:57

+0

你說得對。這是一個登錄會話問題。但我仍然無法測試實際響應(請參閱上面的編輯)。 – croceldon 2012-01-05 20:00:09

0

我得到相同的重定向,直到我意識到我的登錄(用戶)方法是罪魁禍首。從this SO link那兒剽竊,我改變了我的登錄方法:

# 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 

在我的測試:

# 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:我使用Rails 3.0,設計,康康舞和Webrat]

相關問題