megas
megas

Reputation: 21791

Testing in specific namespace

I'm trying to test some classes in namespace, currently I have this code:

describe Server::SessionController do

  it "should create session" do
    Server::LoginController.stub(:authenitcate).and_return(session_id)
    Server::SessionController....
    Server::SessionController....
  end
end

How to get rid of repeatable Server namespace?

Upvotes: 4

Views: 819

Answers (2)

NIA
NIA

Reputation: 2543

While @BernardK gave "the-right-thing" solution that will suit for most cases, there is also a dirty HACK. It may be useful if you have a lot of different Spec files testing different classes from the same namespace, and tired of writing module Your::Long::Namespace ... end in every file and introducing additional identation level (as this may cause giant diffs in your VCS).

So, if you put this...

def Object.const_missing(c)
  if Your::Long::Namespace.const_defined? c
    Your::Long::Namespace.const_get(c)
  else
    raise NameError, "uninitialized constant #{c}"
  end
end

...in your spec_helper.rb, then in every spec using this helper you will be able to use all constants from Your::Long::Namespace (classes are constants too) without prefix and without need to put your specs inside this module. This is very much like C++'s using namespace statement. You can see an example of using this in one of my old projects: definition here, usage example here.

BUT note that:

  • this violates all thinkable OOP principles;
  • you modify the behaviour of all Objects, some code might not expect this;
  • as with C++ using namespace, this causes namespace clutter and possible conflicts;
  • being silent and not taking attention (which is good), this hack is very unobvious and undebugabble (which is very BAD, especially if you have collaborators).

You see, use at your own risk :)

Upvotes: 2

BernardK
BernardK

Reputation: 3734

The RSpec Book ( http://pragprog.com/book/achbd/the-rspec-book ) gives a solution :

3 module Codebreaker
4    describe Game do
5        describe "#start" do

... The second statement declares a Ruby module named Codebreaker.This isn’t necessary in order to run the specs, but it provides some conveniences. For example, we don’t have to fully qualify Game on line 4.

So, try to put your spec inside a Server module. HTH.

Upvotes: 5

Related Questions