如何使用 rspec 为通知消息编写测试用例

How to write a test case using rspec for a notice message

在我的应用程序中,我有一个主题控制器,我需要编写一个测试用例来创建一个新主题。当创建新主题时,它将被重定向到新创建主题的显示页面,并显示一条通知 "Topic was created successfully!"。我需要编写一个测试用例来检查显示的通知是否正确使用 rspec.I 有主题控制器:

 def create
@topic = Topic.new(topic_params)
if (@topic.save)
  redirect_to @topic, :notice => 'Topic was created successfully!'
else
  render :action => 'new'
end
end

主题控制器规范:

it "should create new Topic and renders show" do
    expect {
      post :create,params:{ topic:{topicname: "Tech"} }
    }.to change(Topic,:count).by(1)
    expect(response).to redirect_to(topic_path(id: 1))
   /// expect().to include("Topic was created successfully!")
  end

我已经编写了重定向到显示页面的测试用例。但是我坚持检查我在代码的评论中提到的通知。

你应该这样做

expect(flash[:notice]).to match(/Topic was created successfully!*/)

使用 feature spec(集成测试)而不是控制器规范来测试用户看到的应用程序:

# spec/features/topics.rb
require 'rails_helper'
RSpec.feature "Topics" do
  scenario "when I create a topic with valid attributes" do
    visit '/topics/new'
    fill_in 'Topicname', with: 'Behavior Driven Development' # Adjust this after whatever the label reads
    click_button 'create topic'
    expect(page).to have_content 'Topic was created successfully!'
  end

  scenario "when I create a topic but the attributes are invalid" do
    visit '/topics/new'
    fill_in 'Topicname', with: ''
    click_button 'create topic'
    expect(page).to_not have_content 'Topic was created successfully!'
    expect(page).to have_content "Topicname can’t be blank"
  end
end

虽然您可以查看 flash hash,但无论如何您都应该进行集成测试,因为控制器测试存在缺陷并且不会覆盖路由中的错误,因为大部分应用程序已被删除。

事实上,您可能想要重新考虑使用控制器规范,因为 RSpec 和 Rails 团队都建议改用集成测试。如果您想在比功能规范更低的级别进行测试,请使用 request specs.

参见: