简体   繁体   English

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

[英]How to write a test case using rspec for a notice message

In my application I have a topic controller and I need to write a test case for creating a new topic.在我的应用程序中,我有一个主题控制器,我需要编写一个测试用例来创建一个新主题。 when a new topic is created it will be redirected to the show page of the newly created topic and a notice will be displayed "Topic was created successfully!".创建新话题后,会跳转到新创建话题的展示页面,并提示“话题创建成功!”。 I need to write a test case for checking the displayed notice is correct or not using rspec.I have the topic controller:我需要编写一个测试用例来检查显示的通知是否正确使用 rspec。我有主题控制器:

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

TopicController spec:主题控制器规范:

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

Already I have written test cases for redirecting to show page.我已经编写了重定向到显示页面的测试用例。 But I am stuck with the checking the notice that I have mentioned in a comment in my code.但是我坚持检查我在代码中的评论中提到的通知。

你应该做这样的事情

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

Use a feature spec (an integration test) instead of a controller spec to test the application as seen by the user:使用功能规范(集成测试)而不是控制器规范来测试用户看到的应用程序:

# 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

While you can poke around the flash hash you should have an integration test covering this anyways since controller tests are flawed and will not cover for example errors in the routes since large portions of the application are stubbed out.虽然您可以查看 flash 哈希值,但无论如何您都应该进行集成测试来涵盖这一点,因为控制器测试存在缺陷,并且不会涵盖例如路由中的错误,因为大部分应用程序都被剔除。

In fact you may want to reconsider using controller specs at all since both the RSpec and Rails teams suggest using integration testing instead.事实上,您可能想要重新考虑使用控制器规范,因为 RSpec 和 Rails 团队都建议改用集成测试。 If you want to test at a lower level than a feature spec use request specs .如果您想在低于功能规范的级别进行测试,请使用请求规范

See:看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM