Pergunta

I am trying to test (with rspec) a method that will decide color given a png file. In my application this file is in the /tmp folder. But how do I do that in test?

def decide_background(background, screenshot_path)
  background = background.delete(" ")

  self.screenshot = screenshot_path
  self.background = background

  unless screenshot_path.nil? || screenshot_path.empty?
    image = ChunkyPNG::Image.from_file(screenshot_path)
    background = ImageManipulation::get_bg_from_edges(image).delete(" ")
    unless background.empty?
      self.background = background
    end
  end

  if self.background == 'rgba(0,0,0,0)'
    self.background = 'rgb(255,255,255)'
  end

  self.save
end

This method receives two parameters:
1 - background: String of type 'rgb(0,0,0)'
2 - screenshot_path: Path to where screenshot is stored, located in /tmp/#{name_of_file}

I want to make sure that the method actually stores the correct background. So, I guess I would need to mock ImageManipulation::get_bg_from_edges(image).delete(" ") to avoid the dependency, because I am not testing that method. But how would I do that?

Also, how would I pass the screenshot_path? Should I create a file in my /tmp folder for this unit test?

Foi útil?

Solução

Given that this is a unit test, you should mock from_file. There's no benefit in testing ChunkyPNG; I trust its authors already tested it for you. In your examples for this method:

image = double image # ha, I said "double image"
expect(ChunkyPNG::Image).to receive(:from_file).with(# whatever screenshot path should be) { image }
expect(ImageManipulation).to receive(:get_bg_from_edges).with(image) { # whatever background you like }

You probably want an integration test that hits this code too (in fact I'd have written that first), and then you would actually want an image on the disk to read. Whether you'd need to put it there as part of the integration test setup or whether your app should put it there depends on your app.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top