我想用rspec测试控制器的动作和闪存消息。
操作
def create
user = Users::User.find_by_email(params[:email])
if user
user.send_reset_password_instructions
flash[:success] = "Reset password instructions have been sent to #{user.email}."
else
flash[:alert] = "Can't find user with this email: #{params[:email]}"
end
redirect_to root_path
end
规范
describe "#create" do
it "sends reset password instructions if user exists" do
post :create, email: "email@example.com"
expect(response).to redirect_to(root_path)
expect(flash[:success]).to be_present
end
...
但我有一个错误:
Failure/Error: expect(flash[:success]).to be_present
expected `nil.present?` to return true, got false
发布于 2014-07-24 04:12:22
您正在测试是否存在flash[:success]
,但在控制器中使用的是flash[:notice]
发布于 2015-09-15 02:10:52
测试flash消息的最佳方法是由shoulda gem提供的。
这里有三个例子:
expect(controller).to set_flash
expect(controller).to set_flash[:success]
expect(controller).to set_flash[:alert].to(/are not valid/).now
发布于 2016-07-12 20:55:52
如果您对flash消息的内容更感兴趣,可以使用以下命令:
expect(flash[:success]).to match(/Reset password instructions have been sent to .*/)
或
expect(flash[:alert]).to match(/Can't find user with this email: .*/)
我建议不要检查特定的消息,除非该消息是关键的和/或它不经常更改。
https://stackoverflow.com/questions/24919976
复制相似问题