簡體   English   中英

如何在控制器中測試實例變量的可用性?

[英]How can I test the availability of instance variables in my controller?

我正在使用decent_exposure來呈現一些instance_variables:

expose(:my_custom_variable) { current_user.my_variable }

所以現在這個變量在我的控制器中可以作為my_custom_variable

但是我想通過我的測試確保它在那里。

assert_not_nil my_custom_variable

哪個不起作用。 如果我在我的測試中放置調試器,則無法訪問此變量。 我已經嘗試了以下所有......

@controller.instance_variable_get("@my_custom_variable")
@controller.instance_variable_get("my_custom_variable")
@controller.instance_variable_get(:my_custom_variable)
@controller.assigns(:@my_custom_variable)
assigns(:my_custom_variable)
@controller.get_instance(:my_custom_variable)
@controller.get_instance("my_custom_variable")
@controller.get_instance("@my_custom_variable")

這些都不起作用..有什么想法嗎?

注意:我沒有使用rspec。 這是內置的導軌功能測試。

底部的decent_exposure頁面上有一些示例。

測試

控制器測試仍然很容易。 轉變是你現在設定方法而不是實例變量的期望。 使用RSpec,這主要意味着避免分配和分配。

describe CompaniesController do
  describe "GET index" do

    # this...
    it "assigns @companies" do
      company = Company.create
      get :index
      assigns(:companies).should eq([company])
    end

    # becomes this
    it "exposes companies" do
      company = Company.create
      get :index
      controller.companies.should eq([company])
    end
  end
end

查看規格遵循類似的模式:

describe "people/index.html.erb" do

  # this...
  it "lists people" do
    assign(:people, [ mock_model(Person, name: 'John Doe') ])
    render
    rendered.should have_content('John Doe')
  end

  # becomes this
  it "lists people" do
    view.stub(people: [ mock_model(Person, name: 'John Doe') ])
    render
    rendered.should have_content('John Doe')
  end

end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM