使用Rspec测试上传Paperclip文件

6

我并不是非常关心测试文件上传,但由于我的模型中有validates_attachment_presence等内容,因此rspec发出了警告。

所以现在我在spec中创建带有这些属性的模型,试图让它安静下来:

@attr = {
  :name => "value for name",
  :title => "value for title",
  :content => "value for content",
  :pic_file_name => "example.jpg",
  :pic_content_type => "image/jpg",
  :pic_file_size => "8192",
  :pic_updated_at => nil
}

然而这并不起作用。

我找到了这篇文章:http://fr.ivolo.us/posts/mocking-paperclip-with-rspec 所以我尝试了类似于下面的代码:

Post.should_receive(:save_attached_files).and_return(true)

这也不起作用。我该如何取悦RSpec?


1
可能是 Unit testing paperclip uploads with Rspec (Rails) 的重复问题。 - Tobias Cohen
1个回答

11
如果模型 has_attached_file :pic,你只需要把 pic 属性指向某个文件,一切都应该很顺利。
比如说像这样: @attr = { :pic => File.open(File.join(Rails.root, 'spec', 'fixtures', 'file.png')) }

这在之前对我起作用,但在将 Paperclip 从 2.5.0 升级到 3.1.4 后似乎不再奏效。 - David N. Welton
@DavidN.Welton 你遇到了什么错误(如果有的话)?我对Paperclip 3没有太多经验。 - theIV
解决方法是使用以下代码:mymodel.attachedimage = File.open(....),而不是attachedimage = "file/location/foo.jpg" - David N. Welton
@DavidN.Welton 你最终解决了这个问题吗?我也遇到了同样的问题。 - Jason Swett
@JasonSwett 请看上面的评论 - 您必须传递一个文件句柄而不是文件名。 - David N. Welton
由于有些人遇到了问题,我想更新答案,但已经有一段时间没有使用过 paperclip。可以有人建议一下修改吗?@DavidN.Welton 或许可以帮忙?谢谢! - theIV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接