2009-12-12 24 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 /路徑創建等