2011-12-30 37 views
1

模塊請原諒我的小黃瓜包括在rspec的

Given I have a module called Hello 
And it has a method called world and a class called World 
When I include the module in an RSpec spec 
And I call the method world 
Then it returns "hello world from method" 
But when I create a World class 
Then I get NameError: uninitialized constant World 

module Hello 
    def world 
    p "hello world from method" 
    end 
    class World 
    def initialize 
     p "hello world from class" 
    end 
    end 
end 

describe "hello world" do 
    include Hello 
    it "call method" do 
    world 
    end 

    it "call class" do 
    World.new 
    end 
end 
+0

我想你指定你的問題的方式是混淆的(基於一個回答者不理解它) – r00k 2012-07-13 17:36:52

回答

1

原諒我的小黃瓜,除非你打算別的東西(因爲這是不明確)

When I create a Hello::World class 
Then I get an object of kind Hello::World 

it "should not catch fire on instantiation" do 
    Hello::World.new.should_not be_nil 
end 
+0

沒有我的觀點是我不能稱爲World.new,即使我已經在我的規範中包含了Hello。我會想,包括模塊會讓Hello類可用。 – 2012-01-05 18:07:45

+3

'include'只會添加在模塊上定義的實例方法,而'World.new'則會調用在模塊給定的名稱空間中的類上定義的方法。如果你確實需要一個輔助方法來實例化,那麼就像'def new; World.new;在Hello模塊中應該可以工作(但是令人困惑的是,我會將它命名爲「world_creator」或類似的東西)。當涉及到在名稱空間中調用事物時,我傾向於使用整個名稱空間,因爲它減少了錯誤或引起錯誤的焦慮!:) – iain 2012-01-05 22:33:12