【问题标题】:ActionView::Template::Error: undefined method `image_url' for nil:NilClass when doing integration test with rspec railsActionView::Template::Error: 使用 rspec rails 进行集成测试时,nil:NilClass 的未定义方法“image_url”
【发布时间】: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


【解决方案1】:

错误消息undefined method `image_url' for nil:NilClass 似乎表明@article测试 环境中是nil。这个环境不同于开发环境,开发环境和它的类对象大概就是你在浏览器中看到的。

我希望您可以通过在运行测试之前在测试环境中创建(至少)一篇文章来解决您的问题

  background do
    User.create(name: 'Jane Doe', username: 'jodi')
    Article.create(title: 'Your Title', etc...)
  end

那么这篇文章会在test数据库中持久化,就像用户Jane Doe持久化一样。

顺便说一句,您的功能测试似乎也在隐式测试(至少)索引的两个功能:与文章关联的图像的存在,以及“注销”按钮的存在。如果可能,请考虑将这两个测试分开,或者至少明确地测试两者。

【讨论】:

  • 非常感谢您的洞察力
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 2013-04-10
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多