代码之家  ›  专栏  ›  技术社区  ›  RobertJoseph

从rspec控制器规范中访问控制器实例变量

  •  31
  • RobertJoseph  · 技术社区  · 9 年前

    难道我不应该从我的预期测试中看到在控制器操作中创建的实例变量吗?

    # /app/controllers/widget_controller.rb
    ...
    def show
      @widget = ...
      puts "in controller: #{@widget}"
    end
    ...
    

    --

    # /spec/controllers/widget_controller_spec.rb
    RSpec.describe WidgetController, type: :controller do
    ...
    describe "GET #show" do
      it "assigns the requested widget as @widget" do
        get :show, { :id => 1 } # this is just an example - I'm not hardcoding the id
    
        puts "in spec: #{@widget}"
      end
    end
    ...
    

    下面是我运行该规范时得到的输出:

    controller: #<Widget:0x007f9d02aff090>
    in spec:
    

    我认为我应该访问控制器规范中的@widget,这是错误的吗?

    4 回复  |  直到 9 年前
        1
  •  39
  •   Wes Foster    5 年前

    使用 assigns 方法 ( *注释 : 受让人 现已弃用。信息请参见我的答案底部) :

    it "assigns the @widget"
      expect(assigns(:widget)).not_to be_nil
    end
    

    当然,你可以检查 widget 如你所愿,但没有看到什么 @widget 是你提供的控制器代码,我只是检查了一下 nil

    如果你想 puts 小部件,如您的示例中所示,只需使用 受让人

    puts assigns(:widget)
    

    编辑: 受让人 现已弃用(请参见: https://apidock.com/rails/ActionController/TestProcess/assigns )

    如果要继续使用 受让人 您需要安装 rails-controller-testing 宝石

    否则,您可以使用 轨道控制器测试 gem内部使用: @controller.view_assigns[]

        2
  •  21
  •   stevepentler    6 年前

    # assigns 已弃用。 这里有一个解决方案,可以避免 rails-controller-testing 宝石

    尽管它可以是 code smell 测试控制器中的实例变量,升级您可以利用的旧应用程序 #instance_variable_get .

    Rspec示例: expect(@controller.instance_variable_get(:@person).id).to eq(person_id)

        3
  •  18
  •   Will Clarke    7 年前

    在轨道5中, assigns 现已拆分为一个新的 rails-controller-testing 宝石

    您可以安装gem以继续使用 受让人 ,或者你可以使用 轨道控制器测试 gem内部使用 @controller.view_assigns[] .

        4
  •  0
  •   mechnicov    2 年前

    在新的Rails版本中 rails-controller-testing gem可以通过两种方式访问实例变量:

    • 具有 assigns[:key] / assigns['key']

    • 具有 controller.view_assigns['key']

    As you see assigns ActiveSupport::HashWithIndifferentAccess ,因此您可以同时使用字符串或符号作为键。它是由 regular_writer 方法 Hash ,其中所有带有实例变量的键都是字符串,即 @controller.view_assigns 。但您也可以访问 controller 内部测试

    这里的示例

    require 'rails_helper'
    
    describe SomeController, type: :controller do
      before do
        assign(:some_var, 10)
    
        get :show, params: { id: 1 }
      end
    
      it 'assigns the @some_var'
        expect(assigns['some_var']).to eq 10
        expect(assigns[:some_var]).to eq 10
    
        expect(controller.view_assigns['some_var']).to eq 10
      end
    end