简体   繁体   English

使用rspec在gem中测试控制器

[英]using rspec to test a controller in a gem

Does anyone know how to test a controller of gem in the app using the gem with rspec? 有谁知道如何使用带有rspec的gem在应用程序中测试gem的控制器? I have tried http://codingdaily.wordpress.com/2011/01/14/test-a-gem-with-the-rails-3-stack/ and http://say26.com/rspec-testing-controllers-outside-of-a-rails-application without success. 我已经尝试了http://codingdaily.wordpress.com/2011/01/14/test-a-gem-with-the-rails-3-stack/http://say26.com/rspec-testing-controllers-外部应用程序未成功。

I have a controller in a gem like this: 我在像这样的宝石中有一个控制器:

module mygem
 class PostsController < ::ApplicationController
  def index
    @posts = Posts.find(:all)
    @other_var = 10        
  end
 end
end

And I would like to have a test in my app like spec/controllers/posts_controller_spec.rb 我想在我的应用程序中进行测试,例如spec / controllers / posts_controller_spec.rb

describe PostsController do
  describe "index" do

    it "has posts" do
      get :index
      assigns(:posts).should_not be_nil
    end

    it "has other var" do
      get :index
      assert_equal(10, assigns(:other_var))
    end

  end
end

And my spec_helper.rb 还有我的spec_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'

require File.expand_path("../../config/environment", __FILE__)    
require 'rspec/rails'
require 'rspec/autorun'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|

end

I know rspec isn't really meant for this, and ideas or alternatives would be helpful too. 我知道rspec并不是真的要这样做,想法或替代方法也将有所帮助。

A gem is a gem, an app is an app. 宝石是宝石,应用是应用。 They are different stuff. 他们是不同的东西。

I don't think it's a good practice to mix testing of gem into the app. 我认为将gem的测试混入应用中不是一个好习惯。

Normally you don't need to test a gem because they are usually well tested. 通常,您不需要测试宝石,因为它们通常都经过良好测试。 If you really want to do that or the gem is lack of test, fork the gem and pull it in local, then open its test files and add yours. 如果您真的想这样做,或者gem缺少测试,请分叉gem并将其放在本地,然后打开其测试文件并添加您的文件。 Then you can push it back to improve this gem or end up your own version of gem. 然后,您可以将其推回去以改进此gem或结束自己的gem版本。

If you are writing your own gem, put the tests in gem but not app. 如果您要编写自己的gem,请将测试放入gem,而不是app。

If you want to test some functionalities the gem added to your app, you can test the integrated effect, but don't need unit testing. 如果要测试添加到应用程序中的gem的某些功能,则可以测试集成效果,但不需要单元测试。

Ok I feel dumb now, I just had to add the gem namespace to the controllers. 好的,我现在觉得很蠢,我只需要将gem名称空间添加到控制器即可。 so 所以

describe PostsController do
...
end

becomes 变成

describe mygem::PostsController do
...
end

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

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