2012-01-05 76 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]

相关问题