【问题标题】:How to stub a flash in a RSpec spec?如何在 RSpec 规范中存根闪存?
【发布时间】:2014-09-18 18:04:00
【问题描述】:

在我看来,我在控制器中设置了一个hidden_field_tag,其值为flash。也就是说,流程如下:

控制器:

def home
    flash[:id] = 123
end

查看:

<% form_tag(new_invitee_path) %>
  <%= hidden_field_tag :referer, flash[:id] %>
<% end %>

提交给 new_invitee_path 的参数

{ "referer" => "123" }

我可以确认在手动测试中这可以正常工作,但我不知道如何正确地存根。

在我的测试中我有:

before do
  #set flash
  visit '/home'
  fill_in "rest_of_form"
  click_button "submit_form
end

以下是我尝试为set flash 做的事情以及我收到的错误消息:

flash[:id] = 123 
# OR
flash.now[:id] = 123 
# both render error: undefined local variable or method `flash' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x007fc1040f7d60>

# Have also tried a tactic found online to set flash for response object like this:
visit '/home'
response.flash[:id] = 123
# OR
response.flash.now[:id] = 123
# both render error: undefined local variable or method `response' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x007fe118a38490>

#Have read online that it's a problem with the flash being sweeped, so I tried to stub out the sweep, but am unclear how to set the anonymous controller or whatever correctly
controller.instance_eval{flash.stub!(:sweep)}
flash[:id] = 123 
# OR
flash.now[:id] = 123 
# renders error: undefined local variable or method `flash' for nil:NilClass

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing ruby-on-rails-4 rspec


    【解决方案1】:

    您的规范是功能规范,因此规范环境无法访问闪存之类的东西。不要尝试直接使用闪光灯。相反,理想情况下,测试用户对应用程序的视图是否符合其应有的外观和/或行为,如果闪存值设置为应有的方式。我不会只测试表单中是否存在隐藏字段;我会测试它是否具有提交表单后的效果。这就是功能规范的全部内容:从用户的角度测试应用程序是否可以作为一个整体运行。

    如果闪存值从未在 UI 中使用,只是记录或存储在数据库中,则可以测试日志行或模型对象是否具有存储在闪存中的值。 (这里的用户是管理员,他会查看日志或稍后查看其他内容。)但如果 Flash 确实影响 UI,则最好进行测试。

    【讨论】:

    • 好吧,这很公平,在这种情况下,我想将隐藏值本身设置为 123 以便它通过,并且我可以检查它是否已保存到新对象中。那么在 RSPEC 中有没有办法做到这一点?
    • 真的只是一个硬编码的数字吗?如果是这样,只需将其移动到一个常量并在测试中引用该常量。如果它真的来自一个方法或其他东西,你可以存根该方法,或者在测试中安排一些东西,以便该方法返回你可以在最后断言的数字。
    【解决方案2】:

    这对我来说似乎很有效:

    YourController.any_instance.stub(:flash) { {some: "thing" }}
    

    【讨论】:

    • 这很好用,至少对于控制器规格 - 可惜现在没有更简单的方法!只是对于任何偶然发现这一点的人,较新的语法是allow_any_instance_of(described_class).to receive(:flash).and_return(some: "thing")
    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 2014-04-13
    • 2016-11-11
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多