使用rspec测试gem中的控制器

时间:2013-06-21 14:57:24

标签: ruby-on-rails testing rspec

有没有人知道如何使用带有rspec的gem在应用程序中测试gem的控制器?我尝试http://codingdaily.wordpress.com/2011/01/14/test-a-gem-with-the-rails-3-stack/http://say26.com/rspec-testing-controllers-outside-of-a-rails-application但没有成功。

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

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并不是真正意义上的,而且想法或替代方案也会有所帮助。

2 个答案:

答案 0 :(得分:0)

宝石是宝石,应用程序是应用程序。它们是不同的东西。

我认为将gem测试混合到应用程序中并不是一个好习惯。

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

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

如果您想测试宝石添加到您应用中的某些功能,您可以测试集成效果,但不需要进行单元测试。

答案 1 :(得分:0)

好的,我现在感到愚蠢,我只需要将gem命名空间添加到控制器中。所以

describe PostsController do
...
end

变为

describe mygem::PostsController do
...
end