I get this errormsg from doing tests in Rails 4
Error:
ArticlesControllerTest#test_x:
ActionView::Template::Error: undefined method `state' for nil:NilClass
The error occurs at this line in the view:
<% @articles.each do |article| %>
<div id="article-container">
<div id="article-content">
<ul>
<li> <b>Status:</b> <%= article.status_id %></li>
<li> <b>State:</b> <%= article.state.state %></li
>
The model looks like this for article
belongs_to :user
belongs_to :book, primary_key: :ISBN, foreign_key: :ISBN
has_one :state, primary_key: :states_id, foreign_key: "id"
has_one :status, primary_key: :status_id, foreign_key: "id"
has_and_belongs_to_many :courses
validates :ISBN, presence: true
validates :states_id, presence: true
validates :user_id, presence: true
validates :price, presence: true
validates :status_id, presence: true
This is the article and states table in schema
Article table:
create_table "articles", force: :cascade do |t|
t.string "ISBN"
t.integer "user_id"
t.integer "price"
t.integer "status_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "states_id"
t.index ["states_id"], name: "index_articles_on_states_id"
end
State table:
create_table "states", force: :cascade do |t|
t.string "state"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
The problem is running this test (showing file from top until the test in question):
require 'test_helper'
class ArticlesControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
@article_normal = articles(:normal_article)
@article_admin = articles(:admin_article)
@normal_user = users(:normal_user)
@admin_user = users(:admin_user)
@normal_user.id = @article_normal.user_id
@admin_user.id = @article_admin.user_id
end
test "test x" do
get articles_url
assert_response :success
end
The test provides the error message, while in localhost it works.
EDIT The test database is populated with fixtures.
Article fixtures
normal_article:
ISBN: 9788252179675
user_id: 1
price: 500
states_id: 1
status_id: 1
admin_article:
ISBN: 9788252179675
user_id: 2
price: 400
states_id: 1
status_id: 1
The controller method from article_controller:
# GET /articles
# GET /articles.json
def index
@articles = Article.all
@courses = Course.all
@states = State.all
if params[:search]
@articles = Article.search(params[:search])
else
@articles = Article.all
end
end