[英]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>
您不能(也不應該)測試局部變量。 但是,您可以而且應該測試實例變量,這些變量是以@
開頭的變量。 為此,您使用assigns
helper,將實例變量的名稱作為符號傳遞給它。 如果我們想的實例變量的值@tagged_nodes
,我們稱之為assigns(:tagged_nodes)
注意:
)。
因此,如果您的控制器方法如下所示:
def index
@tagged_nodes = Node.includes(:user_tags).tagged_with(current_user.email)
end
...你將使用@tagged_nodes
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.