Rails 中的单元测试 - 带回形针的模型 [英] unit test in rails - model with paperclip
问题描述
我正在尝试使用回形针为带有图片的模型编写测试.我使用的是默认的测试框架,没有 shoulda 或 rspec.在这种情况下,我应该如何测试它?我真的应该上传文件吗?我应该如何向夹具添加文件?
I'm trying to write a test for a model with a picture, using paperclip. I'm using the test framework default, no shoulda or rspec. In this context, how should I test it? Should I really upload a file? How should I add a file to the fixture?
推荐答案
向模型添加文件非常简单.例如:
Adding file to a model is dead simple. For example:
@post = Post.new
@post.attachment = File.new("test/fixtures/sample_file.png")
# Replace attachment= with the name of your paperclip attachment
在这种情况下,您应该将文件放入您的 test/fixtures
目录中.
In that case you should put the file into your test/fixtures
dir.
我通常在我的 test_helper.rb 中做一个小帮手
I usually make a little helper in my test_helper.rb
def sample_file(filename = "sample_file.png")
File.new("test/fixtures/#{filename}")
end
然后
@post.attachment = sample_file("filename.txt")
如果您使用诸如 Factory Girl 之类的东西而不是装置,这会变得更加容易.
If you use something like Factory Girl instead of fixtures this becomes even easier.
这篇关于Rails 中的单元测试 - 带回形针的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!