简体   繁体   English

Rails 5和Rspec 3.5:局部视图中的application_controller方法

[英]Rails 5 and Rspec 3.5: application_controller method in a view partial

Just started learning Rspec, and I'm trying to test for the existence of the header partial on my Home page, and then later on the rest of my pages. 刚开始学习Rspec,我正在尝试在首页上测试部分标题的存在,然后在其余页面上进行测试。

My header partial uses a current_user method from application_controller.rb 我的头文件部分使用了application_controller.rb中的current_user方法

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

to test whether or not a User is logged in 测试用户是否已登录

  <% 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 %>

Attempting to test my view: 尝试测试我的观点:

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

Returns 返回

 Failure/Error: <% if current_user %>

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

I want to test this both when there is a logged in user and when there isn't, but I'm unsure how to stub this. 我要在有登录用户和没有登录用户时都进行测试,但是我不确定如何对它进行存根。

Any suggestions? 有什么建议么?

In your rails_helper you should have... 在您的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

then in your tests you can do... 然后在您的测试中,您可以...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM