2

Trying to learn Ruby and below is a module I have created in order to test IO Ruby features. When I run the following tests:

    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 

I get this error for both:

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

Here is the Module I am testing. Any help/suggestions would greatly appreciated :)

$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

1 Answer 1

4

Short answer: You can't instantiate modules objects

module A
end

class B
end

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

To test a module you can include it in a object like this

  object = Object.new
  object.extend(TestGem)

Or you can create some example class if your module depends on some class behavior.

Sign up to request clarification or add additional context in comments.

4 Comments

How would you go about writing an rspec test for them?
Or, alternatively, klass = Class.new { include TestGem }; object = klass.new.
@AndrewMarshall Yeah, totally forgot you also could include the module instead of extending. Thanks
For cases like this (usually, during initial stages of development, since the spec isn't very useful really), I usually just go subject { Module } then specify { subject.should be_a Module }. Also, you can include your module directly into your spec and just start calling methods on self

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.