简体   繁体   English

如何编写/运行模型/视图/控制器以外的文件的规格

[英]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. 使用rails和rspec,当我使用带有models / views / controllers的rails generate命令时,很容易让rspec为我生成必要的文件。 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 该模块是/lib/my_module.rb所以我创建了一个规范/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. 我遇到的问题是,当我尝试执行rspec spec/运行my_module_spec.rb文件时,无法找到lib/my_module.rb对我的模块的引用。 What's the right way to do this? 这样做的正确方法是什么?

Just FYI the my_module_spec.rb file does have require 'spec_helper' in it already 仅供参考, my_module_spec.rb文件中已经包含require 'spec_helper'

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 意思是some_method被定义为

def self.some_method
  ...
end

If your module contains instance methods, then use Jasper's solution above. 如果您的模块包含实例方法,那么请使用上面的Jasper解决方案。 Hope that clarifies. 希望澄清一下。

Put the following in your config/application.rb file: 将以下内容放在config/application.rb文件中:

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. 没有任何理由你必须跳过箍才能从RSpec访问你的lib/文件并为它们编写测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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