Rails 3.1 控制器测试中的模拟文件上传

发布于 2024-12-10 20:43:50 字数 642 浏览 1 评论 0原文

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

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

,并且控制器代码调用 params[:file].tempfile.path

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

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

,即 Rails 3.1 自动将 params[:file] 转换为字符串。

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小清晰的声音 2024-12-17 20:43:50

终于找到了this,它告诉我们虽然<返回的东西code>fixture_file_upload 有一个 @tempfile 成员,它缺少 reader 方法。解决如下

  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

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
我的黑色迷你裙 2024-12-17 20:43:50

我是这样绕过去的

upload_file = fixture_file_upload('files/stats_upload.csv', 'text/csv')
upload_file.stubs(:tempfile).returns(upload_file)

I went around this way

upload_file = fixture_file_upload('files/stats_upload.csv', 'text/csv')
upload_file.stubs(:tempfile).returns(upload_file)
孤者何惧 2024-12-17 20:43:50

我提出了一个拉取请求来解决此问题,如果您喜欢,请+1:https:/ /github.com/brynary/rack-test/pull/67

I made a pull request to fix this issue, please +1 if you like it: https://github.com/brynary/rack-test/pull/67

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文