如何在minitest控制器测试期间处理未定义的方法

时间:2015-09-22 20:08:11

标签: ruby-on-rails unit-testing ruby-on-rails-4 tdd minitest

我的比赛模型中有以下方法。

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

在对比赛控制器进行测试时,我收到以下错误:

ActionView :: Template ::错误:nil的未定义方法`username':NilClass

为什么会这样,我该如何解决?

我的规格(最小)可在下面找到。

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

0 个答案:

没有答案