RSpec失败,因为实际重定向有一条flash消息

rec*_*nym 1 redirect rspec ruby-on-rails

ThingsController:

...

respond_to do |format|
  format.html {redirect_to(:action => "new", :notice => "its a good thing!")}  # suspect...
end
Run Code Online (Sandbox Code Playgroud)

当我测试这段代码

  it "should redirect to /employees/new with a success notice" do
    post :create, :employee => Factory.build(:employee).attributes
    response.should redirect_to(:action => "new")
    flash[:notice].should_not be_nil
  end
Run Code Online (Sandbox Code Playgroud)

测试失败,因为它不希望实际重定向有通知.

有什么建议?

Rya*_*igg 13

是的,我有建议:在不同的路线上测试不同的东西.

response.should redirect_to(new_thing_path)
flash[:notice].should eql("its a good thing!")
Run Code Online (Sandbox Code Playgroud)

这样,如果redirect_to失败,它将在该行上失败,如果它flash[:notice]被破坏,它将在该行上失败.

此外,您的测试应该有效.


Mat*_*ins 7

我知道你已经接受了答案,但我想在这里提供更多关于这个问题的见解.原始代码失败的真正原因是:

redirect_to(:action => "new", :notice => "its a good thing!")
Run Code Online (Sandbox Code Playgroud)

基本上与此相同:

url = url_for(:action => "new", :notice => "its a good thing!")
redirect_to(url)
Run Code Online (Sandbox Code Playgroud)

在上面,更容易看到值的url假设:notice是你试图作为URL的一部分传递的参数.你要做的是:notice作为一个选项传递redirect_to,但它与你的其他哈希选项合并形成一个URL.

以下是两种(未经测试的)解决方案:

redirect_to({:action => "new"}, {:notice => "its a good thing!"})
Run Code Online (Sandbox Code Playgroud)

要么:

redirect_to(url_for(:action => "new"), :notice => "its a good thing!")
Run Code Online (Sandbox Code Playgroud)