使用Paperclip进行RSpec控制器测试

7

使用Rails 4.2.0和最新的RSpec,我为我的控制器生成了一个基本测试。我现在遇到的问题是如何在valid_attributes中测试Paperclip图像。

从目前的搜索结果来看,我得到了以下代码(但它不起作用):

let(:valid_attributes) {{name: 'The New Room', description: 'This is the brand new room', size: '250', capacity: '100', price: '650', picture: '#{rails.root}/spec/support/room-controller-valid.jpg', rmcat_id: '1'}}

有其他方法可以做到这一点吗?还是说我需要使用辅助工具才能让Paperclip与RSpec配合使用?

我在终端中收到的错误是:

Failure/Error: room = Room.create! valid_attributes Paperclip::AdapterRegistry::NoHandlerError: No handler found for "\#{rails.root}/spec/support/room-controller-valid.jpg

1个回答

8

尝试设置 Paperclip 的元数据属性,而不是提供实际的 :picture 附件。

...
picture_file_name: 'room-controller-valid.jpg',
...

如果您正在验证附件的内容类型或大小,请设置这些属性:

...
picture_file_name: 'room-controller-valid.jpg',
picture_content_type: 'image/jpeg',
picture_file_size: 1.megabyte,
...

当然,这不会将您的文件传递给控制器,因此您不需要文件即可完成此操作。但是您的模型实例应通过验证。来自Paperclip README

Paperclip will wrap up to four attributes (all prefixed with that attachment's name, so you can have multiple attachments per model if you wish) and give them a friendly front end. These attributes are:

<attachment>_file_name
<attachment>_file_size
<attachment>_content_type
<attachment>_updated_at

By default, only _file_name is required for paperclip to operate. You'll need to add _content_type in case you want to use content type validation.


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