如何在测试操作时将值放入flash中

我正在尝试测试需要存储在flash中的值的操作。

def my_action if flash[:something].nil? redirect_to root_path if flash[:something] return end # Do some other stuff end 

在我的测试中,我做了类似的事情:

 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中没有值。 我猜这是因为没有请求实际发生。

有没有办法为这样的测试设置闪存?

问题是,使用闪存散列的方式意味着它只能用于下一个请求。 为了将flash哈希值设置为测试值,您可以编写如下内容:

 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哈希检查。

我不得不解决一个类似的问题; 我有一个控制器操作,在完成时重定向到两个路径之一,具体取决于散列条目的值。 对于上面的例子,我发现的规范测试是:

 it "should do whatever I had commented out above" do get :my_action, action_params_hash, @current_session, {:something=>true} # Assert something end 

@current_session是一个具有会话特定stuf的哈希值; 我正在使用authlogic。 我发现在[测试Rails应用程序指南[1]中 )中使用get的第四个参数。 我发现同样的方法也适用于删除; 我推测所有其他人。

以下为RoR 4.1工作:

 flash_hash = ActionDispatch::Flash::FlashHash.new flash_hash[:error] = 'an error' session['flash'] = flash_hash.to_session_value get :my_action