mardi 22 septembre 2015

how to handle undefined methods during minitest controller testing

I have following methods in my contest model.

class Contest < ActiveRecord::Base
  has_many :submissions
  has_many :users, through: :submissions

  validates_presence_of :name, :admin_id

  acts_as_votable

  def admin_name
    User.find_by_id(self.admin_id).username
  end

  def tonnage
    self.submissions.sum(:tonnage)
  end

  def contest_type_tr
    I18n.t("contests.contest_type")[self.contest_type]
  end

  def contest_short_descr
    I18n.t("contests.contest_short_descr")[self.contest_type]
  end

end

When doing a test for the contest controller I get the following error:

ActionView::Template::Error: undefined method `username' for nil:NilClass

Why is this and how can I fix it?

My specs (minitest) are available below.

require "test_helper"

describe ContestsController do
  let(:user) { users :default }
  let(:contest) { contests :one }

  it "gets index" do
    get :index
    value(response).must_be :success?
    value(assigns(:contests)).wont_be :nil?
  end

  it "gets new" do
    get :new
    value(response).must_be :success?
  end

  it "creates contest" do
    expect {
      post :create, contest: {  }
    }.must_change "Contest.count"

    must_redirect_to contest_path(assigns(:contest))
  end

  it "shows contest" do
    get :show, id: contest
    value(response).must_be :success?
  end

  it "gets edit" do
    get :edit, id: contest
    value(response).must_be :success?
  end

  it "updates contest" do
    put :update, id: contest, contest: {  }
    must_redirect_to contest_path(assigns(:contest))
  end

  it "destroys contest" do
    expect {
      delete :destroy, id: contest
    }.must_change "Contest.count", -1

    must_redirect_to contests_path
  end
end

Aucun commentaire:

Enregistrer un commentaire