【发布时间】:2020-08-23 14:41:41
【问题描述】:
我是 Rails 的初学者,我正在尝试测试我的 Rails 应用程序
我的页面工作正常,但是在进行集成测试时,我收到了这个错误
User signs in with username
Failure/Error: <div class="art-img" style="background: url(<%= @article.image_url %>); background-size: 100% 100%; background-repeat: no-repeat; background-position: center">
ActionView::Template::Error:
undefined method `image_url' for nil:NilClass
这是带有错误 app/view/home/index
的视图模板 <div class="main-art-con">
<div class="art-img" style="background: url(<%= @article.image_url %>); background-size: 100% 100%; background-repeat: no-repeat; background-position: center">
<div class="content-con">
<h5 class="art-head"><%= @article.title %></h5>
<p class="art-con">
<%= truncate(@article.text, length: 100) %>
</p>
</div>
</div>
</div>
这是包含对象实例的主控制器
class HomeController < ApplicationController
def index
@featured_article = Article.unscoped.order(cached_weighted_total: :desc).limit(1)
@article = @featured_article.last
@categories = Category.all.ordered_by_priority
end
end
测试代码
require 'rails_helper'
feature 'User signs in' do
background do
User.create(name: 'Jane Doe', username: 'jodi')
end
scenario 'with username' do
visit login_path
fill_in 'Username', with: 'jodi'
click_on 'Log in'
expect(page).to have_content 'Log Out'
end
end
【问题讨论】:
-
好像没有文章。可以分享一下测试代码吗?
-
嘿@Didymus Orotayo 我认为你可以这样做:
@article = Article.unscoped.order(cached_weighted_total: :desc).limit(1)在控制器中。如果有的话,这将返回 1 条记录。参考:apidock.com/rails/ActiveRecord/QueryMethods/limit
标签: ruby-on-rails rspec integration-testing