【问题标题】:How to controller test rails 4 engine redirect back to main_app routes如何控制测试 Rails 4 引擎重定向回 main_app 路由
【发布时间】:2014-08-10 20:18:21
【问题描述】:

我在控制器测试我创建的 Rails 引擎时遇到了一些麻烦。我遇到的问题是我似乎无法让 rspec 使用 main_app 路由。

例如,我正在编写以下控制器测试。如果不是 main_app.root_path 返回 nil,测试就会通过。

我的控制器规范中的代码是:

context "successful session creation" do
    let(:user) {FactoryGirl.create :user}

    it 'sets user id session' do
      get :create, use_route: :authenticatable, email: user.email, password: 'password'
      expect(session[:user_id]).to eq user.id
    end
  end
end

在我的控制器中,我有:

def create
  user = Authenticatable::User.find_by(email: params[:email])
  if user && user.login(params[:password])
    session[:user_id] = user.id
    redirect_to main_app.root_path, notice: "You are signed in!"
  else
    flash[:error] = 'Invalid email or password'
    redirect_to authenticatable.sign_in_path
  end
end

我得到的 rspec 失败是:

NameError:
   undefined local variable or method `main_app' for #<RSpec::ExampleGroups::AuthenticatableSessionsController::GETCreate:0x007f9f583d6f18>

我怎样才能让 rspec 使用我可用的所有路由助手。

我的 rails_helper.rb 文件如下:

ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require 'rspec/rails'
require 'factory_girl_rails'
require 'shoulda-matchers'
require 'pry'
require 'database_cleaner'
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }

提前感谢您的任何帮助或建议。

【问题讨论】:

    标签: ruby-on-rails rspec rails-engines


    【解决方案1】:

    好像还有其他人有类似的问题......我没有机会亲自尝试,但看看。

    stack overflow

    def main_app
      Rails.application.class.routes.url_helpers
    end
    
    main_app.root_path
    

    【讨论】:

    • 非常感谢。你的生活品味。我一直在寻找一个将近一周的答案。我尝试使用的最后一件事是 Rails.application.routes.url_helpers.stub(main_app.root_path).and_return 但没有任何运气。
    • 感谢@wintersolutions 在链接到的页面上的回答。我希望我能为此获得荣誉。
    • 你把这个放在哪里?
    【解决方案2】:

    只需将其直接放入控制器测试文件或 Rails 助手中,就像单独的方法一样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-05
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多