【问题标题】:How to write a test case using rspec for a notice message如何使用 rspec 为通知消息编写测试用例
【发布时间】:2019-02-08 03:52:00
【问题描述】:

在我的应用程序中,我有一个主题控制器,我需要编写一个测试用例来创建一个新主题。新建主题时,会跳转到新建主题的展示页面,并提示“主题创建成功!”。我需要编写一个测试用例来检查显示的通知是否正确。我有主题控制器:

 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 规范:

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

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

【问题讨论】:

  • flash变量,你试过了吗?
  • @Зелёный 是的,我用过,但我需要使用简单的通知。
  • 闪现和注意的东西是一样的
  • noticealert 是用于闪存的标准化密钥。
  • 好的,我会试试的

标签: ruby-on-rails rspec notice


【解决方案1】:

你应该这样做

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

【讨论】:

  • 我需要使用简单的通知。
【解决方案2】:

使用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

虽然您可以查看闪存哈希,但无论如何您都应该有一个涵盖此问题的集成测试,因为控制器测试存在缺陷,并且不会涵盖例如路由中的错误,因为大部分应用程序都被删除了。

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

见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    相关资源
    最近更新 更多