NoMethodError:未定义的方法标题'为nil:NilClass

时间:2014-01-27 15:54:53

标签: rspec ruby-on-rails-4 nameerror

我是在rails和rspec上使用ruby的新手

当我尝试为Mymodel Controller执行rspec测试时,我遇到了这个问题。

当我通过浏览器访问页面时,Mymodel按预期工作......但是当我执行rspec测试时失败了!

class MymodelController < ApplicationController
  def show
    @model = Mymodel.find(:first, :conditions => { :title => "Model-Title" } );
  end
end

然后我的rspec测试看起来像

require 'spec_helper'

describe MymodelController do

  describe "GET 'show'" do
    it "assigns @model as Mymodel" do
      get 'show'
      expect(assigns(:model)).to be_a Mymodel
    end

    it "assigns model should have 'Model-Title' as title" do
      get 'show'
      expect(assigns(:model).title).to eq "Model-Title" 
    end

  end

end

任何线索?

谢谢!

编辑:以下是遇到的错误:

Failures: 

1) MymodelsController GET 'show' assigns model should have 'Model-Title' as title 
Failure/Error: expect(assigns(:model).title).to eq("Model-Title") 
NoMethodError: undefined method title' for nil:NilClass  
#./spec/controllers/mymodels_controller_spec.rb:15:in block (3 levels) in <top (required)>' The 

第15行是expect(assigns(:model).title).to eq("Model-Title")

2) MymodelsController GET 'show' assigns @model as mymodel
 Failure/Error: expect(assigns(:model)).to be_a(Mymodel)
   expected nil to be a kind of Mymodel(id: integer, title: string, created_at: datetime, updated_at: datetime)
 # ./spec/controllers/mymodels_controller_spec.rb:10:in `block (3 levels) in <top (required)>'

代码行对应是:expect(assigns(:model)).to be_a(Mymodel)

1 个答案:

答案 0 :(得分:1)

您的测试中没有创建任何Mymodel个实例,因此Mymodel.find可能会返回nil,这会解释您在编辑中显示的错误(对于第一个例子)和你的评论(对于第二个例子)。

您在标题和问题正文中显示的NameError很可能是试图使用assigns(model),但这种方式会失败。