当应用程序可以找到时,rspec无法找到@user

时间:2013-08-16 11:24:33

标签: ruby-on-rails rspec ruby-on-rails-3.2

以下rspec测试文件

require 'spec_helper'

describe EvaluationsController do
render_views

  before(:each) do
    association_attr
  end

  describe "'eval_selektor'" do

    before(:each) do
      @eval_selektor = get :eval_selektor, student_group_id: @student_group
    end

    it "should be successful" do
      @eval_selektor
      response.should be_success
    end

    ...

  end

  ...

end

抛出以下错误:

  1) EvaluationsController 'eval_selektor' should be successful
     Failure/Error: @eval_selektor = get :eval_selektor, student_group_id: @student_group
     NoMethodError:
       undefined method `student_groups' for nil:NilClass
     # ./app/controllers/application_controller.rb:7:in `get_student_group'
     # ./spec/controllers/evaluations_controller_spec.rb:14:in `block (3 levels) in <top (required)>'

来自application_controller中的这个方法:

def get_student_group
  @user = current_user
  @student_group = @user.student_groups.find(params[:student_group_id])
end

起初我觉得也许rspec只是没有从application_controller传递方法,但事实并非如此,因为它可以在错误中看到它。代码在浏览器中工作,如果我在视图中放置<%= @user %>,它会显示正确的用户实例。任何想法为什么rspec无法读取@user?

1 个答案:

答案 0 :(得分:1)

apneadiving让我开始朝着正确的方向前进,在this帖子和this之间,我得到了正确的代码:

  ApplicationController.any_instance.stub(:current_user).and_return(@user)