【问题标题】:How can I test the availability of instance variables in my controller?如何测试控制器中实例变量的可用性?
【发布时间】:2014-02-19 22:07:27
【问题描述】:

我正在使用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。这是内置在 Rails 功能测试中的。

【问题讨论】:

标签: ruby-on-rails functional-testing


【解决方案1】:

在底部的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

【讨论】:

  • 使用 MiniTest 或 TestUnit 应该类似于 assert_equal [company], controller.companies 我想
  • 你管理好了吗?也许您可以包含一个简单但完整的有效测试示例。所以每个人都有针对这个问题的 TestUnit/Minitest 解决方案 =)。
  • 是的,实际上就像你说的那样。 @controller.my_custom_variable
  • 那(minitest)assert assigns :my_custom_variable 呢?
猜你喜欢
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多