2009-12-12 68 views
33

我试图用回形针为带图片的模型编写一个测试。我正在使用测试框架的默认,没有shoulda或rspec。在这种情况下,我应该如何测试它?我应该真的上传一个文件吗?我应该如何将文件添加到灯具?在轨道单元测试 - 带回形针的模型

回答

68

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

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

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

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

def sample_file(filename = "sample_file.png") 
    File.new("test/fixtures/#{filename}") 
end 

然后

@post.attachment = sample_file("filename.txt") 

如果你使用类似Factory Girl,而不是灯具这就变得更容易。

+0

它提供:NoMethodError: 未定义的方法'附件=” – CanCeylan 2012-12-25 12:51:58

+2

@CanCeylan'attachment'是通用的,比如'foo' ;您应该将其替换为您在模型上添加回形针附件时使用的任何名称。 – 2013-02-01 19:34:15

+0

@RicoJones谢谢,在帖子中补充说明。 – 2013-02-01 23:01:46

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 

由于回形针是相当行之有效的,我平时不关注的“上传”行为太多了,除非我做一些不寻常的东西。但我会尝试更多地关注确保附件的配置与其所属的型号相符,以满足我的需求。

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 

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

+0

上的文件路径什么是@valid_attributes? – CanCeylan 2012-12-25 12:54:59

+1

在我的测试案例中,这只是创建模型所需的属性的散列。你可能不需要你自己的测试。 – nowk 2012-12-25 17:26:27

1

我使用FactoryGirl,设置模型。

#photos.rb 
FactoryGirl.define do 
    factory :photo do 
    image File.new(File.join(Rails.root, 'spec', 'fixtures', 'files', 'testimg1.jpg')) 
    description "testimg1 description" 
    end # factory :photo 
end 

然后

# in spec 

before(:each) { @user = FactoryGirl.create(:user, :with_photo) } 

在回形针附件指定其将被保存,即

... 
the_path= "/:user_id/:basename.:extension" 
if Rails.env.test? 
    the_path= ":rails_root/tmp/" + the_path 
end 
has_attached_file :image, :default_url => ActionController::Base.helpers.asset_path('missing.png'), 
:path => the_path, :url => ':s3_domain_url' 

Paperclip.interpolates :user_id do |attachment, style| 
    attachment.instance.user_id.to_s 
end 

...

然后同时测试attachment_definitions(如建议kwon)和Dir.glob检查文件是否已保存

it "saves in path of user.id/filename" do 
    expect(Dir.glob(File.join(Rails.root, 'tmp', @user.id.to_s, @user.photo.image.instance.image_file_name)).empty?).to be(false) 
end 

这样,我敢肯定它的执行正确的directy /路径创建等