在我的应用程序中,我有一个主题控制器,我需要编写一个测试用例来创建一个新主题。创建新主题时,它将被重定向到新创建主题的显示页面,并显示一条通知“主题创建成功!”。我需要编写一个测试用例来检查显示的通知是否正确,或者使用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规范:
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
我已经编写了用于重定向到显示页面的测试用例。但是我坚持检查代码中注释中提到的通知。
答案 0 :(得分:1)
使用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哈希中四处摸索,但由于控制器测试存在缺陷,因此无论如何都应该进行集成测试,并且由于应用程序的大部分被截断,因此不会涵盖例如路由错误。
实际上,您可能要重新考虑使用控制器规格,因为RSpec和Rails团队都建议改为使用集成测试。如果您要以比功能规格更低的级别进行测试,请使用request specs。
请参阅:
答案 1 :(得分:0)
您应该这样做
expect(flash[:notice]).to match(/Topic was created successfully!*/)