Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何使用rspec为通知消息编写测试用例_Ruby On Rails_Rspec_Notice - Fatal编程技术网

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

Ruby on rails 如何使用rspec为通知消息编写测试用例,ruby-on-rails,rspec,notice,Ruby On Rails,Rspec,Notice,在我的应用程序中,我有一个主题控制器,我需要编写一个用于创建新主题的测试用例。创建新主题时,它将被重定向到新创建主题的显示页面,并显示一条通知“topic was created successfully!”。我需要编写一个测试用例来检查显示的通知是否正确,是否使用rspec。我有主题控制器: def create @topic = Topic.new(topic_params) if (@topic.save) redirect_to @topic, :notice => 'Top

在我的应用程序中,我有一个主题控制器,我需要编写一个用于创建新主题的测试用例。创建新主题时,它将被重定向到新创建主题的显示页面,并显示一条通知“topic was created successfully!”。我需要编写一个测试用例来检查显示的通知是否正确,是否使用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
主题控制器规格:

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!*/)
使用(集成测试)而不是控制器规范来测试用户看到的应用程序:

# 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散列进行研究,但无论如何,您都应该有一个集成测试来覆盖这一点,因为控制器测试有缺陷,并且不会覆盖路由中的错误,因为应用程序的大部分都被截短了

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

见:


flash
变量,你试过了吗?@是的,我用过,但我需要简单地使用notice。同样的,flash和notice
notice
alert
都是与flash一起使用的标准化键。好的,我会尝试一下,我需要简单地使用notice。