脚手架生成的 RSpec Controller 规范中的一项测试失败了,在我看来,它似乎总是设计失败,但当然它肯定会成功。
我使用由 rails g scaffold
生成的 RSpec 规范开发了一个 Rails 4 应用程序.
我的 SkillsController
的 Controller 规范要求我为我的模型填写“有效属性”散列和“无效属性”散列,我这样做了。
除了“使用无效参数的 PUT 更新重新渲染‘编辑’模板”外,所有测试均成功:
1) SkillsController PUT update with invalid params re-renders the 'edit' template
Failure/Error: expect(response).to render_template("edit")
expecting <"edit"> but rendering with <[]>
# ./spec/controllers/skills_controller_spec.rb:139:in `block (4 levels) in <top (required)>'
在 Rails 控制台中,我确认了我的
invalid_params
hash 包含无效参数 ( { hack: 'hack' }
)。Controller 调用
skill_params
方法返回一个空散列,因为我的 invalid_params
hash 只包含无效参数。调用
skill.update(skill_params)
带空 skill_params
hash 返回true,所以else
部分永远不会执行,并且不会呈现"new"模板: def update
respond_to do |format|
if @skill.update(skill_params) # empty hash due to invalid params!
format.html { redirect_to @skill, notice: 'Skill was successfully updated.' }
format.json { render :show, status: :ok, location: @skill }
else
format.html { render :edit }
format.json { render json: @skill.errors, status: :unprocessable_entity }
end
end
end
总结一下:规范将带有无效参数的哈希值放入我的 SkillController。 SkillController 的 'skill_params' 清理这个散列,返回一个空的散列。
skill.update
带有空散列是空操作(在控制台上确认),该方法返回 true
.因此,“编辑”模板应该被渲染的断言永远不会是真的,并且带有无效参数的更新操作的默认 Controller 规范永远不会变成绿色。
我在这里缺少什么?
最佳答案
我终于想通了并在这里发布了解决方案,以防其他人发现自己处于相同的情况。
'invalid params' 散列与具有无效属性名称的参数无关,而与无效的属性值有关。
正如@Simone Carletti 在他的回复中指出的那样,无效的属性名称会被简单地忽略/丢弃。
如果将无效值 PUT 到 Controller ,mymodel.update
方法将返回 false,并且 Controller 重定向到 :edit 操作。
因此,为了使生成的规范通过,规范文件顶部的“无效属性”散列应填充有效的属性名称和无效的属性值(例如,如果需要属性,则为 nil)。
关于ruby-on-rails - RSpec Controller 规范在更新时失败,参数无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34230016/