如何使用 Rspec 测试控制器内的局部变量?
How do I test a local variable inside a controller with Rspec?
在我的 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>
您不能(也不应该)测试局部变量。但是,您可以而且应该测试 instance 变量,这些变量以 @
开头。为此,您使用 assigns
帮助程序,将实例变量的名称作为符号传递给它。如果我们想要实例变量的值@tagged_nodes
,我们调用assigns(:tagged_nodes)
(注意:
)。
因此,如果您的控制器方法如下所示:
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)
试试这个代码:
def index
tagged_nodes = Node.includes(:user_tags).tagged_with(current_user.email)
end
您将使用 controller.tagged_nodes
访问 tagged_nodes
expect(controller.tagged_nodes)
.to match Node.includes(:user_tags).tagged_with(u1.email)
在我的 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>
您不能(也不应该)测试局部变量。但是,您可以而且应该测试 instance 变量,这些变量以 @
开头。为此,您使用 assigns
帮助程序,将实例变量的名称作为符号传递给它。如果我们想要实例变量的值@tagged_nodes
,我们调用assigns(:tagged_nodes)
(注意:
)。
因此,如果您的控制器方法如下所示:
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)
试试这个代码:
def index
tagged_nodes = Node.includes(:user_tags).tagged_with(current_user.email)
end
您将使用 controller.tagged_nodes
访问 tagged_nodesexpect(controller.tagged_nodes)
.to match Node.includes(:user_tags).tagged_with(u1.email)