m = require('mochainon')
Promise = require('bluebird')
tmp = Promise.promisifyAll(require('tmp'))
fs = Promise.promisifyAll(require('fs'))
replacefile = require('../lib/replacefile')

describe 'Replacefile:', ->

	describe 'given a mock file', ->

		beforeEach (done) ->
			tmp.fileAsync().spread (path, fd) =>
				@filePath = path
				@contents = '''
					Lorem ipsum dolor sit amet
					Hello World! Hello World!
				'''
				fs.writeFileAsync(@filePath, @contents).then ->
					fs.closeAsync(fd)
			.nodeify(done)

		afterEach (done) ->
			fs.unlinkAsync(@filePath).nodeify(done)

		describe 'given a single match', ->

			it 'should replace the match', (done) ->
				replacefile.replace(@filePath, /ipsum/, 'tempor').then =>
					promise = fs.readFileAsync(@filePath, encoding: 'utf8')
					m.chai.expect(promise).to.eventually.equal '''
						Lorem tempor dolor sit amet
						Hello World! Hello World!
					'''
				.nodeify(done)

		describe 'given multiple matches', ->

			it 'should replace the matches', (done) ->
				replacefile.replace(@filePath, /Hello/g, 'Hey').then =>
					promise = fs.readFileAsync(@filePath, encoding: 'utf8')
					m.chai.expect(promise).to.eventually.equal '''
						Lorem ipsum dolor sit amet
						Hey World! Hey World!
					'''
				.nodeify(done)

		describe 'given no matches', ->

			it 'should keep the file intact', (done) ->
				replacefile.replace(@filePath, /Foo/, 'Bar').then =>
					promise = fs.readFileAsync(@filePath, encoding: 'utf8')
					m.chai.expect(promise).to.eventually.equal '''
						Lorem ipsum dolor sit amet
						Hello World! Hello World!
					'''
				.nodeify(done)
