Ruby-on-rails Rspec 3 如何测试 Flash 消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24919976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rspec 3 how to test flash messages
提问by Mike Andrianov
I want to test controller's action and flash messages presence with rspec.
我想用 rspec 测试控制器的动作和 flash 消息的存在。
action:
行动:
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
spec:
规格:
describe "#create" do
it "sends reset password instructions if user exists" do
post :create, email: "[email protected]"
expect(response).to redirect_to(root_path)
expect(flash[:success]).to be_present
end
...
But I've got an error:
但我有一个错误:
Failure/Error: expect(flash[:success]).to be_present
expected `nil.present?` to return true, got false
采纳答案by rabusmar
You are testing for the presence of flash[:success], but in your controller you are using flash[:notice]
您正在测试 的存在flash[:success],但在您的控制器中您正在使用flash[:notice]
回答by Robin Daugherty
回答by Mugur 'Bud' Chirica
If you are more interested in the content of the flash messages you can use this:
如果您对 Flash 消息的内容更感兴趣,可以使用:
expect(flash[:success]).to match(/Reset password instructions have been sent to .*/)
or
或者
expect(flash[:alert]).to match(/Can't find user with this email: .*/)
I would advise against checking for a specific message unless that message is critical and/or it does not change often.
我建议不要检查特定消息,除非该消息很重要和/或它不经常更改。
回答by killerkiara
With: gem 'shoulda-matchers', '~> 3.1'
和: gem 'shoulda-matchers', '~> 3.1'
The .nowshould be called directly on the set_flash.
本.now应直接在叫set_flash。
Using set_flashwith the nowqualifier and specifying nowafter other qualifiers is no longer allowed.
不再允许set_flash与now限定符一起使用并now在其他限定符之后指定。
You'll want to use nowimmediately after set_flash. For instance:
您会想在now之后立即使用set_flash。例如:
# Valid
should set_flash.now[:foo]
should set_flash.now[:foo].to('bar')
# Invalid
should set_flash[:foo].now
should set_flash[:foo].to('bar').now
回答by Artur Beljajev
The another approach is to leave out the fact that a controller has flash messages and write integration test instead. This way you increase the chances that you will not need to alter the test once you decide to show that message using JavaScript or by some another way.
另一种方法是忽略控制器具有闪存消息的事实,而是编写集成测试。这样一来,一旦您决定使用 JavaScript 或其他方式显示该消息,就可以增加无需更改测试的机会。

