I am trying to test the following method, which given a base64 string, it prints a PNG:
def self.decode64_to_png(src)
if (src.start_with? "data:image/png;base64")
png = Base64.decode64(src['data:image/png;base64,'.length .. -1])
png_logo_uuid = SecureRandom.urlsafe_base64(nil,false)
if Rails.env.production?
src = "#{Rails.root}/tmp/#{png_logo_uuid}.png"
File.open(src, 'wb') { |f| f.write(png) }
else
src = "#{Rails.root}/public/images/#{png_logo_uuid}.png"
File.open(src, 'wb') { |f| f.write(png) }
end
return src
end
end
But I am pretty new to testing and I am trying to figure out what would be the best way to test this in rspec. I know I should have written the test first, but I am still learning. Bu basically I want to make sure that:
1 - Given a correct base64 string, an image is created and src is returned
2 - Given an incorrect base64, nil is returned.
This is the test that I have done so far:
describe ".decode64_to_png" do
it 'returns a path if the source is a correct base64 string' do
File.stub(:open) { true }
src = "data:image/png;base64,iVBORw0KGg"
ImageManipulation.decode64_to_png(src).should_not be_nil
end
it 'returns nil if the source is not a correct base64 string' do
File.stub(:open) { true }
src = "asdasdasdata:image/png;base64,iVBORw0KGg"
ImageManipulation.decode64_to_png(src).should be_nil
end
end