mercredi 28 juin 2017

Rails: Testing file upload validation at model spec

The following code tests image validation within a model spec in a Rails 4.2 app with RSpec 3.5 and the Shrine gem for file uploads.

My questions are:

  • Can you think of a way to improve the following tests or a better way to test those validations?
  • How to improve the speed of the file size validation test? If possible, I'd like to test it without actually having to upload a >10mb file.

Other aspects of the file upload setup are tested in controller and feature specs, which are irrelevant to this question.

RSpec.describe ShareImage, :type => :model do
  describe "#image", :focus do
    let(:image_file) do
      # Could not get fixture_file_upload to work, but that's irrelevant
      Rack::Test::UploadedFile.new(File.join(
        ActionController::TestCase.fixture_path, 'files', filename))
    end
    let(:share_image) { FactoryGirl.build(:share_image, image: image_file) }
    before(:each) { share_image.valid? }

    context "with a valid image file" do
      let(:filename) { 'image-valid.jpg' }
      it "attaches the image to this record" do
        expect(share_image.image.metadata["filename"]).to eq filename
      end
    end

    context "with JPG extension and 'text/plain' media type" do
      let(:filename) { 'image-with-text-media-type.jpg' }
      it "is invalid" do
        expect(share_image.errors[:image].to_s).to include("invalid file type")
      end
    end

    # TODO: Refactor the following test (it takes ~50 seconds to run)
    context "with a >10mb image file" do
      let(:filename) { 'image-11mb.jpg' }
      it "is invalid" do
        expect(share_image.errors[:image].to_s).to include("too large")
      end
    end
  end
end

Aucun commentaire:

Enregistrer un commentaire