我的测试没有成功创建指南,我无法理解原因。
guidelines_controller_test.rb中的测试是
test "should create guideline when logged in" do
sign_in users(:tester)
assert_difference('Guideline.count') do
post :create, guideline: { content: @guideline.content, hospital: @guideline.hospital, title: @guideline.title }
end
我在guidelines_controller.rb中的创建操作是
def create
@guideline = Guideline.new(params[:guideline])
respond_to do |format|
if @guideline.save
format.html { redirect_to @guideline, notice: 'Guideline was successfully created.' }
format.json { render json: @guideline, status: :created, location: @guideline }
else
format.html { render action: "new" }
format.json { render json: @guideline.errors, status: :unprocessable_entity }
end
end
端
当我尝试运行测试时失败
1) Failure:
test_should_create_guideline_when_logged_in(GuidelinesControllerTest) [test/functional/guidelines_controller_test.rb:36]:
"Guideline.count" didn't change by 1.
<4> expected but was
<3>.
并且test.log显示(试图复制相关位)
Processing by GuidelinesController#create as HTML
Parameters: {"guideline"=>{"content"=>"www.test.com", "hospital"=>"Test Hospital", "title"=>"Test title"}}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 781720531 LIMIT 1
(0.1ms) SAVEPOINT active_record_1
Guideline Exists (0.3ms) SELECT 1 AS one FROM "guidelines" WHERE (LOWER("guidelines"."title") = LOWER('Test title') AND "guidelines"."hospital" = 'Test Hospital') LIMIT 1
(0.1ms) ROLLBACK TO SAVEPOINT active_record_1
Rendered guidelines/_form.html.erb (256.5ms)
Completed 200 OK in 313ms (Views: 279.2ms | ActiveRecord: 0.8ms)
(0.2ms) SELECT COUNT(*) FROM "guidelines"
(0.1ms) rollback transaction
有人可以帮忙吗?
答案 0 :(得分:0)
看起来您正在尝试创建一个已存在的标题/医院组合的指南。你得到了正确的日志块 - 这一行:
Guideline Exists (0.3ms) SELECT 1 AS one FROM "guidelines" WHERE [...]
是Rails确保不存在重复的指南(您可能在模型中有“唯一”验证)。它找到匹配项,因此它取消了保存事务:
(0.1ms) ROLLBACK TO SAVEPOINT active_record_1
更改您要插入的标题和/或医院,它应该会很好。
修改强>
根据我们在评论中的对话,我认为问题如下:您正在使用@guideline
初始化@guideline = guidelines(:one)
,这会加载您在灯具文件中定义的名为“one”的指南
但是,当您开始在Rails中运行测试时,它会自动将所有灯具加载到测试DB中。因此,当您尝试使用@guideline
中的属性制作新指南时,您保证会获得重复!
最简单的方法是在测试代码中定义新的属性:
post :create, guideline: {
content: "This is my new content!",
hospital: "Some Random Hospital",
title: "Some Random Title"
}
希望有所帮助!