Testing in a specific namespace

I am trying to test some classes in a 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 a duplicate Server namespace?

+4
source share
2 answers

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 called Codebreaker. It's not necessary to run the specs, but it does provide some convenience. For example, we do not need to fully qualify the game on line 4.

So, try placing your spec inside the Server module. NTN.

+4
source

While @BernardK provided the β€œright” solution, which is suitable for most cases, there is also a dirty HACK. This can be useful if you have many different Spec files that test different classes from the same namespace and are tired of writing module Your::Long::Namespace ... end in each file and introduce an additional level of identification (so how this can lead to gigantic differences 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 each specification with this helper you can use all the constants from Your::Long::Namespace (classes are also constants) without a prefix and without the need to enter your specifications inside this module. This is very similar to a C ++ statement using namespace . You can see an example of using this in one of my old projects: definition here , here .

COMMENT:

  • it violates all conceivable principles of OOP;
  • you change the behavior of all objects, some of them may not expect this;
  • as with C ++ using namespace , this causes using namespace clutter and possible conflicts;
  • it is silent and does not pay attention (which is good), this hack is very unobvious and invulnerable (which is very bad, especially if you have co-authors).

You see, use at your own risk :)

+2
source

All Articles