簡體   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