Created
July 27, 2012 22:44
-
-
Save Sam-Serpoosh/3190871 to your computer and use it in GitHub Desktop.
This is a little helper method which take the path of a file relative to rails root directory and "require" that file in the test. Comes handy for the isolated tests in a rails project. Interestingly enough, I wrote this via TDD too!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#you can use this easily like the following in your spec files: | |
reuqire_relative "../spec_helper_lite" | |
reuqire_relative_to_root "lib/some_domain_logic" | |
describe "some domain logic" do | |
#specs will be here then | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def require_relative_to_root(file_path) | |
rails_root = find_rails_root(File.dirname(__FILE__)) | |
require(File.expand_path("#{rails_root}/#{file_path}")) | |
end | |
def find_rails_root(dir) | |
return dir if is_root?(dir) | |
find_rails_root(File.expand_path(dir + "/../")) | |
end | |
def is_root?(directory) | |
entries = Dir.entries(directory) | |
return entries.include?("app") && | |
entries.include?("spec") && | |
entries.include?("config") | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require_relative "../spec_helper_lite" | |
describe "test_helper_lite" do | |
it "knows when directory is root" do | |
root_dir = File.expand_path(File.dirname(__FILE__) + "/../../../") # according to the current directory structure of the app and where the current file exists | |
is_root?(root_dir).should be_true | |
end | |
it "knows when directory is not root" do | |
not_root_dir = File.dirname(__FILE__) | |
is_root?(not_root_dir).should be_false | |
end | |
it "goes one level back to find the root" do | |
current_directory = File.expand_path(File.dirname(__FILE__) + "/../") | |
root_dir = find_rails_root(current_directory) | |
is_root?(root_dir).should be_true | |
end | |
it "goes back as many level as needed to find the root directory" do | |
current_directory = File.dirname(__FILE__) | |
root_dir = find_rails_root(current_directory) | |
is_root?(root_dir).should be_true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment