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

推荐答案

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

Ruby-on-rails相关问答推荐

Rails 7中的Turbo流

Sweet Alert 2 在 Rails 7 应用程序中无法正常工作

如何将动态 Ruby 代码嵌入到 Slim 模板中的javascript部分?

使用 RSpec 和 Capybara (Rails) 测试重定向

FactoryGirl + Faker - 为数据库种子数据中的每个对象生成相同的数据

Rails 3:如何正确显示textarea中的文本?

如何在 Rails 迁移中添加判断约束?

为什么 respond_with 被从 rails 4.2 移除到它自己的 gem 中?

错误未初始化的常量 AWS (NameError)

将图标添加到 Rails 应用程序

控制器 helper_method

我们如何在 Rails Mailer 中设置邮箱发件人的名称?

使用 rvm 更新 ruby​​ 版本后收到警告消息Path set to RVM

如何将 ActionMailer default_url_options 的 :host 动态设置为请求的主机名?

Postgresql JSON 数据列不同

使用 heroku 和 namecheap 设置自定义域

Ruby 安装的 RVM 不工作?

没有路由匹配缺少必需的键:[:id]

Ruby/Rails CSV 解析,UTF-8 中的无效字节序列

我什么时候需要在 Rails 中重新启动服务器?