How to Unit Test namespaced models
Asked Answered
P

3

6

In my Rails app, I make heavy use of subdirectories of the model directory and hence of namespaced models - that is, I have the following directory heirarchy:

models
|
+- base_game
|  |
|  +- foo.rb (defines class BaseGame::Foo)
|
+- expansion
   |
   +- bar.rb (defines class Expansion::Bar) 

This is enforced by Rails - that is, it Just Doesn't Work to call the classes "just" Foo and Bar.

I want to unit test these classes (using Shoulda on top of ActiveSupport::TestCase). I know that the name of the class-under-test will be derived from the name of the test case class.

How do I write unit tests that will test these classes?

Piteous answered 29/7, 2011 at 14:40 Comment(0)
P
4

Turns out it is straight-forward, even under normal ActiveSupport / Test::Unit. Simply duplicate the model directory structure under /test:

test
|
+- base_game
|  |
|  +- foo_test.rb (defines class BaseGame::FooTest)
|
+- expansion
   |
   +- bar_test.rb (defines class Expansion::BarTest) 
Piteous answered 31/7, 2011 at 18:14 Comment(0)
I
2

This should work directly, I use Rspec and it's straight:

describe User::Profile do

  it "should exist" do
    User::Profile.class.should be_a Class
  end

  it { should validate_presence_of(:name) }

end
Insecurity answered 29/7, 2011 at 16:46 Comment(0)
M
0

Here's some code that worked for me with both ruby -I and zeus:

require "test_helper"

class BaseGame::Foo < ActiveSupport::TestCase
  include BaseGame

  should "let #baz do something" do
    assert Foo.new.baz
  end

end

You can also do

require "test_helper"

class BaseGame::Foo < ActiveSupport::TestCase

  should "let #baz do something" do
    assert BaseGame::Foo.new.baz
  end

end
Musjid answered 27/11, 2014 at 19:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.