简体   繁体   中英

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? 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.

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

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

# 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.

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.

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. Then you can push it back to improve this gem or end up your own version of gem.

If you are writing your own gem, put the tests in gem but not 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.

Ok I feel dumb now, I just had to add the gem namespace to the controllers. so

describe PostsController do
...
end

becomes

describe mygem::PostsController do
...
end

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