有一个名为课程的模型,用户可以参加,因此我有@user.courses
- 它适用于static-pages-home的视图,因为它允许我通过部分列出的课程列出课程下面。但是我的rspec测试结果出错了。
控制器
class StaticPagesController < ApplicationController
def home
@user = current_user
@courses = @user.courses
end
end
Rspec错误
1) Static pages should have the right links on the layout
Failure/Error: visit root_path
NoMethodError:
undefined method `courses' for nil:NilClass
# ./app/controllers/static_pages_controller.rb:4:in `home'
# ./spec/requests/static_pages_spec.rb:55:in `block (2 levels) in <top (required)>'
Rspec Spec
require 'spec_helper'
describe "Static pages" do
subject { page }
describe "Home page" do
before { visit root_path} <<<error here (rb:55)
end
end
查看部分(有效)
<div class="row">
<div class="span8">
<% if @courses.any? %>
<ul class="courses">
<%- @courses.each do |course| %>
<%= link_to course.title, course_path(course) %>
<%- end%>
</ul>
<% end %>
</div>
</div>
答案 0 :(得分:0)
因为它是静态页面控制器,有时用户存在,有时用户还不存在。因此,如果我将变量更改为仅在用户为signed_in时才相关,则它可以正常工作。
def home
@courses = current_user.courses if signed_in?
end