简体   繁体   中英

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

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

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.

Put the following in your config/application.rb file:

config.autoload_paths += %W(#{Rails.root}/lib)

I was just wrestling with the same problem, and the above worked for me. There's not really any reason you should have to jump through hoops to be able to access your lib/ files from RSpec and write tests for them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM