基于缺少会话变量的Rails测试失败-如何在Rails 5.2中进行设置?

时间:2018-11-24 12:07:19

标签: ruby-on-rails

我有一个以下非常简单的测试,它一直通过。

  test "should get index" do
    sign_in @user 
    get companies_url
    assert_response :success
  end

但是,我现在收到以下错误。

Error:
CompaniesControllerTest#test_should_get_index:
ActionView::Template::Error: No route matches {:action=>"show", :controller=>"companies", :id=>nil}, missing required keys: [:id]
    app/views/layouts/application.html.erb:53:in `_app_views_layouts_application_html_erb__2582383126246718868_70101260952060'
    test/controllers/companies_controller_test.rb:16:in `block in <class:CompaniesControllerTest>'

我在应用程序中所做的更改是,我已经构建了一个侧边栏(我通过application.html.erb加载了侧边栏,因此该侧边栏已加载到所有视图(新建,显示,编辑)上,从而允许用户在各种视图之间进行切换他们“拥有”的公司-更改了会话变量,我们用它来更改侧边栏的内容。

如果我们深入研究似乎未通过app/views/layouts/application.html.erb:53的行,它就是它的样子:

<div class="list-group-item">
   <%= link_to 'Company', company_path(session[:current_company]) unless current_user.companies.empty? %>
</div>

如果我删除此link_to行,则测试通过。

我的猜测是show视图正在尝试加载,包括没有设置session[:current_company]的边栏,因此视图崩溃。但是,据我所知,在Rails 5.2中无法设置/测试会话变量,所以我想知道对我而言设置测试通过的最佳方法是什么?我确实在application controller用户登录的范围内为此会话设置了一个值:

  def after_sign_in_path_for(resource_or_scope)
    # Set a default current company scope for a use after signing in
    session[:current_company] = current_user.companies.first.id unless current_user.companies.empty?
    companies_path
  end

也许是在边栏中的link_to中,我可以添加一个默认值以确保无论是否是session[:current_company],我们总是在发送公司信息。

我真的很坚持这一点-感谢您的帮助!谢谢!

1 个答案:

答案 0 :(得分:0)

如果没有会话变量,则更改该行以跳过创建链接

<%= link_to 'Company', company_path(session[:current_company]) unless current_user.companies.empty? || !session[:current_company] %>

似乎可以解决问题,并通过所有测试。很乐意就这是否是一个好的解决方案提供一些反馈! :)