【问题标题】:Trouble including controller macros for rspec tests /w devise包含用于 rspec 测试 /w 设计的控制器宏的问题
【发布时间】:2015-11-29 07:55:37
【问题描述】:

我得到一个未初始化的常量 ControllerMacros (NameError),可能类似于这些问题(123)。我在尝试包含控制器宏时一定搞砸了语法,这样我就可以使用设计登录并在 rspec 中通过控制器测试。 Link to GitHub repoRails 4.1.8 和 Ruby 2.1.2

spec/controllers/static_pages_controller_spec.rb

require 'rails_helper'


describe StaticPagesController, :type => :controller do
  describe "GET #index" do
    it "responds successfully with an HTTP 200 status code" do
      login_user
      get :index
      expect(response).to be_success
      expect(response).to have_http_status(200)
    end

    it "renders the index template" do
      login_user
      get :root
      expect(response).to render_template("index")
    end
  end

end

spec/support/controller_macros.rb

module ControllerMacros
  def login_admin
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:admin]
      admin = FactoryGirl.create(:admin)
      sign_in :user, admin # sign_in(scope, resource)
    end
  end

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      user = FactoryGirl.create(:user)
      user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
      sign_in user
    end
  end
end

spec/rails_helper

中添加了行
   #helps avoid authentication error during rspec:
    config.include Devise::TestHelpers, :type => :controller
    config.include ControllerMacros, :type => :controller

【问题讨论】:

    标签: ruby-on-rails ruby rspec devise macros


    【解决方案1】:

    这对我有用。

    spec/support/devise.rb

    require 'devise'
    
    RSpec.configure do |config|
     config.include Devise::TestHelpers, :type => :controller
     config.extend ControllerMacros, :type => :controller
    end
    

    还要确保该行在 rails_helper.rb 中未注释

    Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
    

    【讨论】:

      【解决方案2】:

      您可能需要将require 'support/controller_macros' 添加到您的rails_helper.rb 文件的顶部。默认情况下,该目录不会包含在 RSpec 中。

      【讨论】:

      • 我不敢相信这么容易。
      • 为我添加 config.extend ControllerMacros, :type => :controller 工作
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      相关资源
      最近更新 更多