Billy Logan
Billy Logan

Reputation: 2520

How to test image preview with Capybara?

I have js code that displays an image preview after adding a picture.

 function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
          $('#preview').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}
$(document).ready(function(){
  $("#attach").change(function () {
      readURL(this);
  });
});

And html:

<img id="preview" style="width:400px;height:400px;">

<label for="attach">
  <span>Click to add picture</span>
</label>

<input class="hidden" id="attach" type="file" name="profile[image]">

Check out Codepen example.

Question: Using capybara how can I test that image preview shows up when I attach a picture? I know we can check img tag for a src but how can I combine Capybara with Javascript code?

Simply using attach_file() doesn't do anything useful here since Capybara isn't friendly with JS.

Upvotes: 1

Views: 752

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49870

I'm not sure what you mean about Capybara not being friendly with JS, however there is an inconsistency in your example since your file input has an id of "attach" and your JS change listener is listening on '#inputFile' - assuming that is fixed (in this code I assumed the input id was supposed to be 'attach') then you can do

execute_script('$("#attach").removeClass("hidden")') #make input visible so you can attach to it
attach_file('attach', 'some_file.jpg') #attach the file
expect(page).to have_css('#preview[src]') #confirm a src attribute was set

Upvotes: 1

Related Questions