Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write/run specs for files other than model/view/controller

Using rails and rspec it's easy to have rspec generate the necessary files for me when I'm using the rails generate command with models/views/controllers. But now I want to write specs for a module I wrote. The module is in /lib/my_module.rb so I created a spec in /spec/lib/my_module_spec.rb

The problem I'm having is that when I try to do rspec spec/ the file my_module_spec.rb is run but the reference to my module in lib/my_module.rb can't be found. What's the right way to do this?

Just FYI the my_module_spec.rb file does have require 'spec_helper' in it already

require 'spec_helper'

describe "my_module" do
  it "first test"
    result = MyModule.some_method  # fails here because it can't find MyModule
  end
end
like image 462
Brand Avatar asked Dec 08 '11 12:12

Brand


2 Answers

You could try including the module and maybe wrapping it in an object

require 'spec_helper'

#EDIT according to 
# http://stackoverflow.com/users/483040/jaydel
require "#{Rails.root}/lib/my_module.rb"

describe MyModule do

  let(:wrapper){
    class MyModuleWrapper
      include MyModule
    end
    MyModuleWrapper.new
  }

  it "#some_method" do
    wrapper.some_method.should == "something"
  end

end
like image 105
Jasper Avatar answered Nov 09 '22 22:11

Jasper


Does your module contain class methods or instance methods? Remember that only class methods will be available via

MyModule.some_method

meaning that some_method is defined as

def self.some_method
  ...
end

If your module contains instance methods, then use Jasper's solution above. Hope that clarifies.

like image 43
agranov Avatar answered Nov 09 '22 21:11

agranov