无法使用rspec获取控制器实例变量

时间:2016-12-22 15:36:37

标签: ruby-on-rails rspec

我有简单的控制器:

class CreditLogsController < BaseController

  def show
    @account = Account.find_by_email(Base64.urlsafe_decode64(params[:id]))
  end
end

以下是它的规格:

require 'rails_helper'

describe CreditLogsController, type: :controller do

  describe 'GET #show' do
    it 'responds with 200' do
      create(:account)

      get :show, params: {id: Base64.urlsafe_encode64('tes1@test.com')}, format: :html
      puts "############# #{controller.instance_variable_get(:account)}"
      expect(assigns(:account)).to eql('tes1@test.com')
    end
  end

end

问题是规范中的account始终为nil,在控制器的覆盖文件代码中,将值分配给@account显示为未涵盖且controller.instance_variable_get(:account)引发错误:

  

`account'不允许作为实例变量名。

我在其他规范中有类似的代码并且工作正常,所以我做错了什么?

1 个答案:

答案 0 :(得分:-1)

如错误所示,该实例变量名称错误。它们必须以@开头,描述它们的符号和字符串也是如此。

您必须使用:

controller.instance_variable_get(:@account)

controller.instance_variable_get('@account')

您的其他测试(expect(assigns(:account))...)将无法联系到,因为instance_variable_get(:account)会引发NameError例外。