Didymus Orotayo
Didymus Orotayo

Reputation: 75

ActionView::Template::Error: undefined method `image_url' for nil:NilClass when doing integration test with rspec rails

I am a beginner in rails and I am trying to test my rails app

My page works fine but when doing the integration tests, I get this error

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

Here is the view template with the error 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>

This is my home controller containing the object instance

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

Code for the test

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

Upvotes: 0

Views: 800

Answers (1)

Jarmo
Jarmo

Reputation: 191

The error message undefined method `image_url' for nil:NilClass would seem to indicate that @article is nil in the test environment. This environment is distinct from the development environment, and the development environment and its class objects are presumably what you see in your browser.

I expect you can fix your problem by creating (at least) one article in the test environment before running the test:

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

Then this article will persist in the test database, in the same manner as user Jane Doe persists.

As an aside, it also seems that your feature test is implicitly testing (at least) two features of the index: the presence of an image associated with the article, and the presence of the Log Out button. If possible, consider separating these two tests, or at least explicitly testing for both.

Upvotes: 1

Related Questions