ruby-on-rails - 如何使用 Rspec / Rails 5.2 在分层父子关系中测试子创建?
问题描述
我的应用程序管理 BusinessFlows,它只能在父 BusinessArea 中创建。BusinessFlows 控制器中的“新”方法是:
def new
@business_area = BusinessArea.find(params[:business_area_id])
@business_flow = BusinessFlow.new
end
用于测试的 Factory 工作正常,并按预期创建父 BusinessArea 和 BusinessFlow:
FactoryBot.define do
factory :business_flow do
association :parent, factory: :business_area
playground_id {0}
name {"Test Business Flow"}
code {Faker::Code.unique.rut}
description {"This is a test Business Flow used for unit testing"}
created_by {"Fred"}
updated_by {"Fred"}
owner_id {0}
responsible_id {0}
deputy_id {0}
organisation_id {0}
status_id {0}
end
end
但是在测试是否可以显示“新”视图时,由于缺少参数 [:business_area_id],控制器会引发错误:
ActiveRecord::RecordNotFound: Couldn't find BusinessArea without an ID
这是功能测试脚本:
require 'rails_helper'
RSpec.describe BusinessFlow, type: :request do
include Warden::Test::Helpers
describe "Business Flows pages: " do
let(:bf) {FactoryBot.create(:business_flow)}
context "when not signed in " do
it "should propose to log in when requesting index view" do
get business_flows_path
follow_redirect!
expect(response.body).to include('Sign in')
end
it "should propose to log in when requesting new view" do
get new_business_flow_path
follow_redirect!
expect(response.body).to include('Sign in')
end
it "should propose to log in when requesting edit view" do
get edit_business_flow_path(bf)
follow_redirect!
expect(response.body).to include('Sign in')
end
it "should propose to log in when requesting show view" do
get business_flow_path(bf)
follow_redirect!
expect(response.body).to include('Sign in')
end
end
context "when signed in" do
before do
get "/users/sign_in"
test_user = FactoryBot.create(:user)
login_as test_user, scope: :user
end
it "should display index" do
get business_flows_path
expect(response).to render_template(:index)
end
it "should display new view" do
get new_business_flow_path(bf.parent.id)
expect(response).to render_template(:_form)
end
it "should display edit view" do
get edit_business_flow_path(bf)
expect(response).to render_template(:_form)
end
it "should display show view" do
get business_flow_path(bf)
expect(response).to render_template(:show)
end
end
end
end
只有“登录时”上下文中的“新”方法测试失败。你能帮我解决这个问题吗?
非常感谢!
解决方案
it "should display new view" do
get new_business_flow_path(business_area_id: bf.parent)
expect(response).to render_template(:_form)
end
Rails 认为您传递的 id 是业务流程路径的一部分(实际上不是),我认为它需要作为参数传递。
推荐阅读
- java - 在 java fx 中滚动列表视图时避免 updateItem
- javascript - 将此 PCRE 转换为 Javascript 正则表达式
- javascript - 保护元素免受全局 CSS
- c# - 将异步方法传递给 Parallel.ForEach
- python - Joblib Parallel + Cython 永远挂起
- javascript - threejs 一个一个加载 obj
- c# - Azure CosmosDB SQL API createDatabaseAsync 不创建数据库
- java - 编辑maven的设置文件
- ios - iOS - 如何 - startMonitoringSignificantLocationChanges 工作
- java - 带有 EditTexts 的 RecyclerView - 添加新行