0

My test is not successfully creating a guideline and I cannot work out why.

The test in guidelines_controller_test.rb is

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

My create action in guidelines_controller.rb is

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

end

when I try to run the test it fails

     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>.

and the test.log shows (have tried to copy the relevant bit)

 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

Can anyone help?

4

1 回答 1

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 中运行测试时,它会自动将所有的固定装置加载到测试数据库中。因此,当您尝试使用 中的属性创建新指南时@guideline,您一定会得到重复!

解决此问题的最简单方法是在测试代码中内联定义新属性:

post :create, guideline: {
    content:  "This is my new content!",
    hospital: "Some Random Hospital",
    title:    "Some Random Title"
}

希望有帮助!

于 2013-02-09T10:56:59.113 回答