# Detect environment in migration

**URL:** <https://www.ruby-forum.com/t/detect-environment-in-migration/121467>\
**Category:** Rails\
**Created:** [November 28, 2007, 7:28am UTC](https://www.ruby-forum.com/t/detect-environment-in-migration/121467 "2007-11-28T07:28:45Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexmic](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/977dab/32.png) [@alexmic](https://www.ruby-forum.com/u/alexmic)\
**Post date:** [November 28, 2007, 7:28am UTC](https://www.ruby-forum.com/t/detect-environment-in-migration/121467/1 "2007-11-28T07:28:45Z")

</div>

We’re using migrations for generating our test schemas (for a whole load  
of reasons) and need to specifically run code when we are running our  
rspec tests as opposed to running the actual migrations on the  
production or development boxes.

Is there a way to detect the current environment that rspec is  
connecting too?

I’ve tried looking in ENV[‘RAILS\_ENV’] but it doesn’t appear to be set.  
I’ve also tried looking in ActiveRecord::Base.connection to see if the  
connection would give me a clue.

I want to do something like:

if RAILS\_ENVIRONMENT == ‘TEST’

# RUN THIS SQL

end

---

<div class="post-metadata">

**Author:** ![alexmic](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/977dab/32.png) [@alexmic](https://www.ruby-forum.com/u/alexmic)\
**Post date:** [November 28, 2007, 1:29pm UTC](https://www.ruby-forum.com/t/detect-environment-in-migration/121467/2 "2007-11-28T13:29:58Z")

</div>

Alex M. wrote:

> Is there a way to detect the current environment that rspec is  
> connecting too?

I’m not sure if this is helpful, but I use the following code to  
generate development and test databases for a system that I report on  
only in Rails (the production database is part of another application).  
This works for me:

def self.up  
if ENV[“RAILS\_ENV”] and ENV[“RAILS\_ENV”] == “production”  
puts “Production db not altered by migration”  
else  
sql = “CREATE TABLE …” #creation SQL code.  
execute sql  
end  
end
