测试动作时如何将值放入闪存中 [英] How to put a value in flash when testing an action
问题描述
我正在尝试测试需要将值存储在闪存中的操作.
I'm trying to test an action that needs a value stored in flash.
def my_action
if flash[:something].nil?
redirect_to root_path if flash[:something]
return
end
# Do some other stuff
end
在我的测试中,我做了类似的事情:
In my test I do something like:
before(:each) do
flash[:something] = "bob"
end
it "should do whatever I had commented out above" do
get :my_action
# Assert something
end
我遇到的问题是 flash 在 my_action 中没有值.我猜这是因为实际上没有发生任何请求.
The problem I'm running into is that flash has no values inside of my_action. I'm guessing this is because no request actually happens.
有没有办法为这样的测试设置闪光灯?
Is there a way to set flash up for a test like this?
推荐答案
问题在于,按照您的方式使用 flash 散列意味着它只能用于下一个请求.为了将 flash 散列设置为测试值,您可以编写如下内容:
The problem is that using the flash hash the way you do means it only becomes avaialble for the next request. In order to set the flash hash to a value for your test, you could write something like this:
def test_something_keeps_flash
@request.flash[:something] = 'bar'
xhr :get, :my_action
assert_response :success
// Assert page contents here
end
这可确保您可以检查操作的逻辑.因为它现在会正确设置 flash 哈希,所以输入您的 my_action 并对 flash 哈希执行检查.
This ensures that you can check the logic of your action. Because it will now set the flash hash properly, enter your my_action and perform the check on the flash hash.
这篇关于测试动作时如何将值放入闪存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!