Ruby: exception wrongly raised when testing the creation of a directory
<p>I have a module named FileSystem in my app, which executes basic filesystem functionality. Here is the relevant code of it.</p>

<pre><code>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
</code></pre>

<p>And this is my Rspec test for this feature</p>

<pre><code>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
</code></pre>

<p>It happens that when I run my tests I got this error</p>

<pre><code>expected StandardError with "Database already exists", got #&lt;Errno::EEXIST: File exists @ dir_s_mkdir - txtdb/testedb&gt;
</code></pre>

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

<p>==========</p>

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

<pre><code>def self.create_database(db)
  fpdb = db_full_path(db)
  if (valid_parameter?(db) and valid_database?(fpdb)) then
    Dir.mkdir(fpdb)
  end
end
</code></pre>

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