我的测试没有成功创建指导原则,我无法找出原因。
guideline_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
我在guideline_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
有人能帮忙吗?
看起来您正试图创建一个标题/医院组合已经存在的指南。你得到了正确的日志-这一行:
Guideline Exists (0.3ms) SELECT 1 AS one FROM "guidelines" WHERE [...]
Rails确保不存在重复的准则(您的模型中可能有一个"唯一"的验证)。它找到匹配项,因此取消保存事务:
(0.1ms) ROLLBACK TO SAVEPOINT active_record_1
更改您要插入的标题和/或医院,它应该会顺利通过。
编辑:
根据我们在评论中的对话,我认为问题如下:您正在用@guideline = guidelines(:one)
初始化@guideline
,它加载您在fixture文件中定义的名为"one"的指导方针。
但是,当您开始在Rails中运行测试时,它会自动将所有的fixture加载到测试数据库中。因此,当您尝试使用@guideline
中的属性创建新的指导方针时,保证会得到重复!
最简单的方法是在测试代码中定义新的属性:
post :create, guideline: {
content: "This is my new content!",
hospital: "Some Random Hospital",
title: "Some Random Title"
}
希望能有所帮助!