在Rails 3.1控制器测试中嘲笑文件上传 [英] Mocking file uploads in Rails 3.1 controller tests

查看:184
本文介绍了在Rails 3.1控制器测试中嘲笑文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器访问上传文件的 tempfile 属性,并将其传递给另一个模拟组件。我的测试代码有

$ p $ @file = mock(Object)
@ file.stub_chain(:tempfile,:path) .and_return('thefile.zip')
#...
post:create,:file => @file

和控制器代码调用 params [:file] .tempfile。路径



从Rails 3.0升级到3.1之后,上面的行开始失败。

 未定义的方法`tempfile'为#[RSpec :: Mocks :: Mock:0x2b0d9a0 @ name = Object]:String 

也就是说,Rails 3.1将 params [:file] 自动转换为一个字符串。



当通过浏览器手动测试时,代码正常工作。我尝试使用 fixture_file_upload ,并且该参数变成了 File 对象,但它没有 tempfile 方法。

那么如何将一个任意的模拟对象作为参数传递给Rails 3.1中的一个动作?

解决方案

最后找到这个,它表明尽管由 fixture_file_upload 返回的东西有一个 @tempfile 成员,缺少读者的方法。解决如下:

  FileUtils.touch('file.zip')#fixture_file_upload需要文件存在
@file = fixture_file_upload('file.zip')
class<< @file
#reader方法存在于实际调用中,
#但是由于某种原因从fixture对象中缺少(Rails 3.1.1)
attr_reader:tempfile
end


My controller accesses the tempfile attribute of an uploaded file and passes it to another mocked component. My test code has

  @file = mock(Object)
  @file.stub_chain(:tempfile, :path).and_return('thefile.zip')
  # ...
  post :create, :file => @file

and the controller code calls params[:file].tempfile.path.

After upgrading from Rails 3.0 to 3.1, the above line started failing with

undefined method `tempfile' for "#[RSpec::Mocks::Mock:0x2b0d9a0 @name=Object]":String

That is, Rails 3.1 converted params[:file] to a string automatically.

The code works properly when tested manually through a browser. I tried to use fixture_file_upload and the parameter became a File object but it had no tempfile method.

So how do I pass an arbitrary mock object as a parameter to an action in Rails 3.1?

解决方案

Finally found this, which tells that although the thing returned by fixture_file_upload has a @tempfile member, it lacks the reader method. Solved as follows

  FileUtils.touch('file.zip') # fixture_file_upload needs the file to exist
  @file = fixture_file_upload('file.zip')
  class << @file
    # The reader method is present in a real invocation,
    # but missing from the fixture object for some reason (Rails 3.1.1)
    attr_reader :tempfile
  end

这篇关于在Rails 3.1控制器测试中嘲笑文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆