轨道单元测试 - 带回形针的模型

VP.*_*VP. 33 ruby unit-testing ruby-on-rails paperclip

我正在尝试使用回形针为带有图片的模型编写测试.我正在使用测试框架默认,没有shoulda或rspec.在这种情况下,我该如何测试呢?我应该真的上传文件吗?我该如何在夹具中添加文件?

Max*_*yak 68

将文件添加到模型非常简单.例如:

@post = Post.new
@post.attachment = File.new("test/fixtures/sample_file.png")
# Replace attachment= with the name of your paperclip attachment
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您应该将文件放入您的test/fixtures目录.

我通常在test_helper.rb中做一个小帮手

def sample_file(filename = "sample_file.png")
  File.new("test/fixtures/#{filename}")
end
Run Code Online (Sandbox Code Playgroud)

然后

@post.attachment = sample_file("filename.txt")
Run Code Online (Sandbox Code Playgroud)

如果你使用像Factory Girl这样的东西而不是夹具,这就变得更容易了.

  • @CanCeylan`additional`是通用的,就像`foo`; 您应该在模型上添加Paperclip附件时使用您使用的任何名称替换它. (2认同)

now*_*owk 16

这是在Rspec,但可以很容易地切换

before do # setup
  @file = File.new(File.join(RAILS_ROOT, "/spec/fixtures/paperclip", "photo.jpg"), 'rb')
  @model = Model.create!(@valid_attributes.merge(:photo => @file))
end

it "should receive photo_file_name from :photo" do # def .... || should ....
  @model.photo_file_name.should == "photo.jpg"
  # assert_equal "photo.jpg", @model.photo_file_name
end
Run Code Online (Sandbox Code Playgroud)

由于Paperclip经过了很好的测试,我通常不会过分关注"上传"的行为,除非我做了一些与众不同的事情.但我会更多地关注确保附件的配置与其所属的模型相关,满足我的需求.

it "should have an attachment :path of :rails_root/path/:basename.:extension" do
  Model.attachment_definitions[:photo][:path].should == ":rails_root/path/:basename.:extension"
  # assert_equal ":rails_root/path/:basename.:extension", Model.attachment_definitions[:photo][:path]
end
Run Code Online (Sandbox Code Playgroud)

所有的好东西都可以找到Model.attachment_definitions.