Skip to content

Instantly share code, notes, and snippets.

@toddmohney
Last active November 4, 2016 19:54
Show Gist options
  • Save toddmohney/1c88cbcc5568f919afe21f03c7603057 to your computer and use it in GitHub Desktop.
Save toddmohney/1c88cbcc5568f919afe21f03c7603057 to your computer and use it in GitHub Desktop.
Namespaces in test

I've been bitten by this on multiple projects now.

Take the following test setup for the class Accounts::Analytics::Account

module Accounts
  module Analtyics
    describe Account do

    end
  end
end

Keep in mind that there is a top-level Account class, as well.

Now, there's a subtle, but tricky difference between declaring your test's context this way:

module Accounts
  module Analytics
    describe Account do
      ...

And this way:

describe Accounts::Analytics::Account do

Here goes...

In the first example, if the test loads before the class loads, the test defines the namespace. Then when it encounters Account in the test, it finds nothing in its own namespace (because it hasn't been autoloaded yet), so it pops out to the top and finds the equivalent of ::Account. This is the WRONG one!

In the second example, the test loads, tries to find the fully-qualified Accounts::Analytics::Account, doesn't find any part of the namespace, so it loads the whole thing and you get the right one.

If we like the module..module..describe style, the solution is to fully qualify the object under test. Alternatively, I think requiring the file would also work.

Computers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment