我正在使用Rspec运行Rails测试,对于重定向的操作,它正在检查重定向页面,而不是最终目标页面。这是有道理的,但它不是我想要的。我想确保呈现一条flash消息。是否无法使用have_selector正确测试重定向目标中的最终视图?例如,一个简单的创建操作:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@page_title = @user.name
end
def create
@user = User.new(params[:user])
if @user.save
flash[:success] = "You have successfully signed up!"
redirect_to @user
else
flash[:error] = "There were errors signing up."
@page_title = "Sign Up"
render 'new'
end
end
在此测试下失败:
it "should have flash message to notify user that signup was successful" do
post :create, :user => @attr
response.should have_selector("div.flash-success")
end
出现此错误:
Failure/Error: response.should have_selector("div.flash-success")
expected following output to contain a <div.flash-success/> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>You are being <a href="http://test.host/users/1">redirected</a>.</body></html>
环境:
答案 0 :(得分:1)
这是测试Flash消息的方法:
it "should have flash message to notify user that signup was successful" do
post :create, :user => @attr
flash[:success].should eql "You have successfully signed up!"
end
答案 1 :(得分:-1)
您是否考虑使用shoulda-matchers
来测试带有rspec的控制器。它们允许您使用以下内容轻松测试Flash消息。
it { should set_the_flash.to(/created successfully/i) }
您不必在页面上查询选择器。作为奖励,您将获得一组用于测试路线,重定向,渲染,布局和HTTP响应的其他匹配器。我发现在使用它时更容易追踪问题。
如果听起来有点帮助,请参阅shoulda-matchers。