2013-02-22 156 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