Ruby: exception wrongly raised when testing the creation of a directory

I have a module named FileSystem in my app, which executes basic filesystem functionality. Here is the relevant code of it.

module TxtDB
  module FileSystem

    def self.create_database(db)
      fpdb = db_full_path(db)
      Dir.mkdir(fpdb) unless ((not valid_parameter?(db)) or (not valid_database?(fpdb)))
    end

    private 

    def self.valid_parameter?(db)
      raise TxtDB::NIL_PARAMETER_ERROR unless (not db == nil)
      raise TxtDB::NOT_A_STRING_ERROR unless (db.is_a? String)
      raise TxtDB::EMPTY_PARAMETER_ERROR unless (not db.empty?)
      true
    end

    def self.valid_database?(db)
      raise TxtDB::DATABASE_ALREADY_EXISTS_ERROR unless (not Dir.exist?(db_full_path(db)))
      true
    end

    def self.db_full_path(db)
      "#{TxtDB::BASE_DIRECTORY}/#{db}"
    end

  end
end

And this is my Rspec test for this feature

it 'raises a StandardError (Database already exists) if it receives the name of an existing database' do
  base_path = TxtDB::BASE_DIRECTORY
  if (not Dir.exist?(base_path)) then
    Dir.mkdir(base_path)
  end
  db_path = File.join(TxtDB::BASE_DIRECTORY,'testedb')
  if (not Dir.exist?(db_path)) then
    Dir.mkdir(db_path)
  end
  expect {
    TxtDB::FileSystem::create_database('testedb')
  }.to raise_error(StandardError, TxtDB::DATABASE_ALREADY_EXISTS_ERROR)
end

It happens that when I run my tests I got this error

expected StandardError with "Database already exists", got #<Errno::EEXIST: File exists @ dir_s_mkdir - txtdb/testedb>

As I see things, this should not happen, since I'm testing for the existence before calling Dir.mkdir. But I'm obviously wrong, since the error occurs. The question is: Where am I wrong?

==========

According to the suggestion of Peter Alfvin (see answer below), I change my method to

def self.create_database(db)
  fpdb = db_full_path(db)
  if (valid_parameter?(db) and valid_database?(fpdb)) then
    Dir.mkdir(fpdb)
  end
end

Now there is no doubt the validations are done beforehand. But I still get the same error.

Upvotes: 0

Views: 71

Answers (1)

Peter Alfvin
Peter Alfvin

Reputation: 29389

Dir.exists?(path) returns true if path is a directory, otherwise it returns false. In valid_database?, you are passing it the full path name, which I would guess is pointing to a non-directory file.

See http://ruby-doc.org/core-2.1.2/Dir.html#method-c-exists-3F

Upvotes: 1

Related Questions