如何在控制器中测试实例变量的可用性



我正在使用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

最新更新