2013-02-22 159 views
2

試圖學習Ruby及以下版本是我爲了測試IO Ruby功能而創建的模塊。當我運行以下測試:初始化Ruby模塊

subject{TestGem.new}  

    it 'should be_a Module' do 
     subject.is_a Module 
    end 

    it 'creates a config file' do 
     subject.init_config 
     File.open("program.config", "r") { |io| io.readline }.should eq "default_file.txt"  
    end 

我得到這個錯誤兩種:

Failure/Error: subject{TestGem.new} 
NoMethodError: 
    undefined method `new' for TestGem:Module 

這裏是我的測試模塊。任何幫助/建議將不勝感激:)

$LOAD_PATH.unshift File.expand_path("../test_gem", __FILE__) 

require 'version' 
require 'hello' 

module TestGem 

    @default_file_name 
    @supported_types 

    def initialize 
    default_file_name = 'default_file.txt' 
    supported_types = ['txt', 'pdf'] 
    end 

    puts "module TestGem defined" 

    def self.init_config 
    File.open('program.config', "w") do |f| 
     f.write(yaml(@default_file_name)) 
     f.write(yaml(@supported_types)) 
    end 
    end 

    class MyFile 

    def self.first(filename) 
     File.open(filename, "r") {|f| f.readline} 
    end 

    def self.last(filename) 
     File.open(filename, "r")[-1] 
    end 
    end 

    class MyError < StandardError 
    puts "Standard Error" 
    end 
end 

回答

3

簡短的回答:你不能實例化對象的模塊

module A 
end 

class B 
end 

B.methods - A.methods #=> [:new, :superclass, :allocate] 

要測試一個模塊,您可以將其包含在這樣

object = Object.new 
    object.extend(TestGem) 
一個對象

或者你可以創建一些例子類,如果你的模塊取決於某些類的行爲。

+0

你會如何去爲他們編寫rspec測試? – NealR 2013-02-22 03:33:39

+0

或者,'klass = Class.new {include TestGem}; object = klass.new'。 – 2013-02-22 03:56:54

+0

@AndrewMarshall是的,完全忘了你也可以包含模塊而不是擴展。謝謝 – 2013-02-22 04:14:49