2012-09-25 110 views
2

我有照片模式和我通過CarrierWave實現文件上傳(我的應用程序的偉大工程):的Rails 3 + CarrierWave + Rspec的:模型驗證

class Photo < ActiveRecord::Base 
    attr_accessible :description, :image 

    mount_uploader :image, ImageUploader 

    validates :description, :length => { :maximum => 500, :message => :max_lenght_message } 
    validates :image, :presence => { :message => :presence_message } 
end 

現在我想在我的模型規範該模型檢查與給定路徑圖像會保存(我上載在一個給定的路徑中的文件):

require 'spec_helper' 

describe Photo do 
    before(:each){ @attr = { :description => "some text is here", :image => "#{Rails.root}/spec/fixtures/files/violin.jpg" } } 

    describe "DB" do 
    it "should create with valid params" do 
     expect do 
     Photo.create(@attr) 
     end.should change(Photo, :count).by(1) 
    end 
    end 
end 

但是,這並不工作:

1) Photo DB should create with valid params 
    Failure/Error: Photo.create(@attr) 
    CarrierWave::FormNotMultipart: 
     You tried to assign a String or a Pathname to an uploader, for security reasons, this is not allowed.   
    If this is a file upload, please check that your upload form is multipart encoded. 

什麼是正確的處理方式?

回答

10

我解決了這個問題:使用

before(:each){ 
    @attr = { :description => "some text is here", 
      :image => File.open(File.join(Rails.root, '/spec/fixtures/files/violin.jpg')) } 
} 
+0

即時通訊解決方案,並得到同樣的錯誤如上:(**編輯,是在犯傻,不理我upvoted ** – Dakuan