【问题标题】:Rails 5 and Rspec 3.5: application_controller method in a view partialRails 5 和 Rspec 3.5:部分视图中的 application_controller 方法
【发布时间】:2017-04-02 08:47:27
【问题描述】:

刚开始学习 Rspec,我正在尝试在我的主页上测试部分标题是否存在,然后在我的其余页面上测试。

我的部分标头使用 application_controller.rb 中的 current_user 方法

def current_user
  @current_user ||= User.find_by(id: session[:user_id])
end

测试用户是否登录

  <% if current_user %>
    <%= image_tag(current_user.image_url, size: "30", :class => "profile_image") %>
  <% end %>
  <ul class="nav navbar-nav navbar-right">
    <li><%= link_to "Home", root_path %></li>
    <% if current_user %>
      <li><%= link_to "TODOs", todos_path %></li>
      <li><%= link_to "Log Out", logout_path, method: :delete %></li>
    <% else %>
      <li><%= link_to "Log In", 'auth/google' %></li>
    <% end %>

试图测试我的观点:

require 'rails_helper'

RSpec.describe "home_page/home.html.erb", type: :view do
  context "When viewing the home page" do

    it "the home page should render the _header partial" do
      render :partial => "layouts/header"

      expect(view).to render_template(:partial => 'header')
    end

  end
end

返回

 Failure/Error: <% if current_user %>

 ActionView::Template::Error:
   undefined local variable or method `current_user' for #<#<Class:0x007fc9d85409f8>:0x007fc9d77a4858>
   Did you mean?  current_page?

我想在有登录用户和没有登录用户的情况下对此进行测试,但我不确定如何存根。

有什么建议吗?

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    在您的rails_helper 中,您应该有...

    require 'devise'
    
    RSpec.configure do |config|
      # For Devise <= 4.1.0
      # config.include Devise::Test::ControllerHelpers, :type => :controller
      # Use the following instead if you are on Devise >= 4.1.1
      config.include Devise::TestHelpers, :type => :controller
    end
    

    那么在你的测试中你可以做...

    before(:each) do
      user = User.create(name: 'John') # <-include other params as req'd
      user.confirm! # if you're using devise's confirmable module
      sign_in user
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2017-05-09
      • 2018-12-08
      • 1970-01-01
      相关资源
      最近更新 更多