RubyonRails-Rspec 3.8,Rails 5,FacotryBot POST重定向测试失败



我在这里学习Ruby on Rails restaurantly教程:http://rubyonrailstutor.github.io/.首先,我不得不做出一些改变,主要是通过试错和在线搜索错误。这在很大程度上是因为这是一个关于Ruby和Rails旧版本的旧教程。

我使用的是rails 5.2.1和Ruby 2.5.3,以及大多数gem的最新版本。我已经成功完成了本教程,直到这里找到的最后一个rspec测试:http://rubyonrailstutor.github.io/new/restaurants-new-create/.

当我运行rspec spec/requests/restaurants_spec.rb时,我得到以下错误:

Failures:
1) RestaurantsController POST /restaurants complete params redirects to show
Failure/Error: expect(subject).to redirect_to restaurant_path(id:1)
Expected response to be a redirect to <http://www.example.com/restaurants/1> but was a redirect to <http://www.example.com/restaurants/new>.
Expected "http://www.example.com/restaurants/1" to be === "http://www.example.com/restaurants/new".
# ./spec/requests/restaurant_spec.rb:32:in `block (4 levels) in <top (required)>'
Finished in 0.60375 seconds (files took 1.47 seconds to load)
5 examples, 1 failure
Failed examples:
rspec ./spec/requests/restaurant_spec.rb:31 # RestaurantsController POST /restaurants complete params redirects to show

我的控制器与教程作者使用的控制器相同:https://github.com/rubyonrailstutor/restaurantly/blob/restaurants-new/app/controllers/restaurants_controller.rb.

我的规范文件中失败的部分是:

context "POST /restaurants" do
context "complete params" do
subject{ post "/restaurants", params: { name: "mcrails"}}
it "redirects to show" do
expect(subject).to redirect_to restaurant_path(id:1)
end 
end 
context "incomplete params" do
subject{ post "/restaurants", {}} 
it "redirects to new" do
expect(subject).to redirect_to(new_restaurant_path)
end 
end 
end 

我的主题与作者使用它的方式略有不同,我想知道这是我错的地方。当我遇到一些参数错误时,我更改了它,我认为这是由于版本控制的差异。原件看起来是这样的:

restaurant = {restaurant: {name: "mcrails"}}
subject{ post "/restaurants", restaurant }

我已经改成这个:

subject{ post "/restaurants", params: { name: "mcrails"}}

作者关于rails 4的规范文件:https://github.com/rubyonrailstutor/restaurantly/blob/restaurants-new/spec/requests/restaurant_spec.rb.

当我运行web服务器并创建一个新项目时,它会重定向到#正确显示项目。但是rspec测试失败。所以我认为我没有正确运行测试。也许是由于版本差异和我传递的参数,但我无法理解这一点。在这一点上,我的Rails经验非常少。

@MarkMerritt向我介绍了一些文档,这些文档帮助我进行了一些反复试验,找出了如何使其发挥作用。

虽然我仍然不完全理解教程和我能够完成的工作之间的语法差异,但我会发布我的最终规范文件编辑,以防有人有任何反馈。

context "POST /restaurants" do
context "complete params" do
subject { post "/restaurants", :params => { :restaurant => { :name => "mcrails" } } } 
it "redirects to show" do
expect(subject).to redirect_to restaurant_path(:id => assigns(:restaurant).id) 
end 
end 
context "incomplete params" do
subject { post "/restaurants", :params => {} } 
it "redirects to new" do
expect(subject).to redirect_to(new_restaurant_path) 
end 
end 
end

相关内容

  • 没有找到相关文章

最新更新