gpt4 book ai didi

ruby-on-rails - 如何使用 Rspec 测试 Controller 内的局部变量?

转载 作者:行者123 更新时间:2023-12-02 17:11:42 25 4
gpt4 key购买 nike

在我的Dashboard#Index中,我有这个:

  def index        
tagged_nodes = Node.includes(:user_tags).tagged_with(current_user.email)
end

如何使用 RSpec 对此进行测试?

我尝试过:

  expect(assigns(tagged_nodes)).to match Node.includes(:user_tags).tagged_with(u1.email)

但这给了我这个错误:

 NameError:
undefined local variable or method `tagged_nodes' for #<RSpec::ExampleGroups::DashboardController::GETIndex:0x007fe4edd7f058>

最佳答案

您不能(也不应该)测试局部变量。但是,您可以而且应该测试实例变量,这些变量以@开头。为此,您可以使用 assigns 帮助器,将实例变量的名称作为符号传递给它。如果我们想要实例变量@tagged_nodes的值,我们调用assigns(:tagged_nodes)(注意:)。

因此,如果您的 Controller 方法如下所示:

def index        
@tagged_nodes = Node.includes(:user_tags).tagged_with(current_user.email)
end

...您可以使用assigns(:tagged_nodes)访问@tagged_nodes:

expect(assigns(:tagged_nodes))
.to match Node.includes(:user_tags).tagged_with(u1.email)

关于ruby-on-rails - 如何使用 Rspec 测试 Controller 内的局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30040569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com