Pra*_*n R 5 rspec ruby-on-rails notice
在我的应用程序中,我有一个主题控制器,我需要编写一个测试用例来创建一个新主题。当一个新话题被创建时,它会被重定向到新创建话题的显示页面,并会显示一条通知“话题已成功创建!”。我需要编写一个测试用例来检查显示的通知是否正确使用 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
Run Code Online (Sandbox Code Playgroud)
主题控制器规范:
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
Run Code Online (Sandbox Code Playgroud)
我已经编写了重定向到显示页面的测试用例。但是我坚持检查我在代码中的评论中提到的通知。
你应该做这样的事情
expect(flash[:notice]).to match(/Topic was created successfully!*/)
Run Code Online (Sandbox Code Playgroud)
使用功能规范(集成测试)而不是控制器规范来测试用户所看到的应用程序:
\n\n# spec/features/topics.rb\nrequire \'rails_helper\'\nRSpec.feature "Topics" do\n scenario "when I create a topic with valid attributes" do\n visit \'/topics/new\'\n fill_in \'Topicname\', with: \'Behavior Driven Development\' # Adjust this after whatever the label reads\n click_button \'create topic\'\n expect(page).to have_content \'Topic was created successfully!\'\n end\n\n scenario "when I create a topic but the attributes are invalid" do\n visit \'/topics/new\'\n fill_in \'Topicname\', with: \'\'\n click_button \'create topic\'\n expect(page).to_not have_content \'Topic was created successfully!\'\n expect(page).to have_content "Topicname can\xe2\x80\x99t be blank"\n end\nend\nRun Code Online (Sandbox Code Playgroud)\n\n虽然您可以研究闪存哈希,但无论如何您都应该进行一个涵盖这一点的集成测试,因为控制器测试是有缺陷的,并且不会涵盖例如路由中的错误,因为应用程序的大部分都被删除了。
\n\n事实上,您可能需要重新考虑使用控制器规范,因为 RSpec 和 Rails 团队都建议使用集成测试。如果您想在低于功能规范的级别进行测试,请使用请求规范。
\n\n看:
\n\n\n| 归档时间: |
|
| 查看次数: |
1781 次 |
| 最近记录: |