【问题标题】:Rspec 3 how to test flash messagesRspec 3 如何测试闪存消息
【发布时间】:2014-09-15 04:44:45
【问题描述】:

我想用 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

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    您正在测试flash[:success] 的存在,但在您的控制器中您使用的是flash[:notice]

    【讨论】:

    • 哦,对不起,我刚刚滑到这里了。与 flash[:notice] 相同的错误
    • 在这种情况下,问题可能出在您的控制器代码和/或测试数据上。尝试将expect(flash[:notice]) 更改为expect(flash[:alert]),如果测试通过,则可能只是测试电子邮件不存在。
    【解决方案2】:

    shoulda gem 提供了测试 Flash 消息的最佳方法。

    这里是三个例子:

    expect(controller).to set_flash
    expect(controller).to set_flash[:success]
    expect(controller).to set_flash[:alert].to(/are not valid/).now
    

    【讨论】:

      【解决方案3】:

      如果您对 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: .*/)
      

      我建议不要检查特定消息,除非该消息很关键和/或它不经常更改。

      【讨论】:

        【解决方案4】:

        另一种方法是忽略控制器具有闪存消息这一事实,而改为编写集成测试。这样一来,一旦您决定使用 JavaScript 或其他方式显示该消息,您就无需更改测试的机会。

        另见https://stackoverflow.com/a/13897912/2987689

        【讨论】:

          【解决方案5】:

          与:gem 'shoulda-matchers', '~> 3.1'

          .now 应该直接在set_flash 上调用。

          不再允许将set_flash 与now 限定符一起使用并在其他限定符之后指定now。

          您需要在set_flash 之后立即使用now。例如:

          # 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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-06-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-02-08
            相关资源
            最近更新 更多