[rspec-users] Another RSpec on Rails issue: how to test send_file()

s.ross cwdinfo at gmail.com
Sat Dec 30 19:45:26 EST 2006


Well, here's one I just dealt with. The spec might not be great, but  
here it is:

# in spec_helper.rb (this code is taken pretty much intact from the  
Wiki article on testing uploads

       # get us an object that represents an uploaded file
       def uploaded_file(path, content_type="application/octet- 
stream", filename=nil)
         filename ||= File.basename(path)
         t = Tempfile.new(filename)
         FileUtils.copy_file(path, t.path)
         (class << t; self; end;).class_eval do
           alias local_path path
           define_method(:original_filename) { filename }
           define_method(:content_type) { content_type }
         end
         return t
       end

       # a JPEG helper
       def uploaded_jpeg(path, filename=nil)
         uploaded_file(path, 'image/jpeg', filename)
       end

       # a GIF helper
       def uploaded_gif(path, filename=nil)
         uploaded_file(path, 'image/gif', filename)
       end

       # a CSV helper
       def uploaded_csv(path, filename=nil)
         uploaded_file(path, 'text/csv', filename)
       end

# in your spec

     setup do
         get_logged_in
         @upload_file = uploaded_csv("#{File.expand_path(RAILS_ROOT)}/ 
spec/fixtures/upload_test.csv")
         @upload_record_count = File.open("#{File.expand_path 
(RAILS_ROOT)}/spec/fixtures/upload_test.csv").readlines("\r").size - 1
         @original_size = Member.count
     end

     specify "the upload method should receive a good file" do
         @upload_file = uploaded_csv("#{File.expand_path(RAILS_ROOT)}/ 
spec/fixtures/upload_test.csv")
         post :upload, :member_file => @upload_file
         response.should_be_success
         Member.count.should == @original_size + @upload_record_count
         m = Member.find_by_first_and_last('Blake', 'Park')
         m.should_not_be_nil
         m.created_on.year.should_be > 2000
     end

     specify "the upload method should reject bogus data in a file" do
         @upload_file = uploaded_csv("#{File.expand_path(RAILS_ROOT)}/ 
spec/fixtures/upload_bogus_test.csv")
         post :upload, :member_file => @upload_file
         response.should_be_success
         response.should_have_tag :p, :content => /upload data error/
     end


Comments welcomed.

Steve

On Dec 30, 2006, at 3:00 PM, Tobias Grimm wrote:

> Hi!
>
> Today I needed to implement some controller code, that uses  
> send_file()
> to send image data. How can this be tested / specified with RSpec?
>
> bye,
>
> Tobias
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users



More information about the rspec-users mailing list