繁体   English   中英

使用rspec在gem中测试控制器

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

有谁知道如何使用带有rspec的gem在应用程序中测试gem的控制器? 我已经尝试了http://codingdaily.wordpress.com/2011/01/14/test-a-gem-with-the-rails-3-stack/http://say26.com/rspec-testing-controllers-外部应用程序未成功。

我在像这样的宝石中有一个控制器:

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

我想在我的应用程序中进行测试,例如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

还有我的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

我知道rspec并不是真的要这样做,想法或替代方法也将有所帮助。

宝石是宝石,应用是应用。 他们是不同的东西。

我认为将gem的测试混入应用中不是一个好习惯。

通常,您不需要测试宝石,因为它们通常都经过良好测试。 如果您真的想这样做,或者gem缺少测试,请分叉gem并将其放在本地,然后打开其测试文件并添加您的文件。 然后,您可以将其推回去以改进此gem或结束自己的gem版本。

如果您要编写自己的gem,请将测试放入gem,而不是app。

如果要测试添加到应用程序中的gem的某些功能,则可以测试集成效果,但不需要单元测试。

好的,我现在觉得很蠢,我只需要将gem名称空间添加到控制器即可。 所以

describe PostsController do
...
end

变成

describe mygem::PostsController do
...
end

暂无
暂无

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

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