Я начинаю работать с Agile Web Development с Rails 4, где мы (читатели) создаем демонстрационное приложение для стиля корзины покупок. Таким образом, далеко основные ресурсы REST: 1) продукты, 2) тележки и 3) позиции. Это мое второе приложение demo/sample на моем пути к обучению Rails, и все кажется прямолинейным до сих пор, за исключением того, что я постоянно получаю ошибку в своих тестах для обновления действия в контроллере позиций. Я не уверен, является ли это ошибкой, связанной с самим тестом, действительным действием контроллера и/или настройками моих настроек. (. Я использую «встроенный» MiniTest с сантехникой в первый раз, предыдущий пример приложения я использовал RSpec и FactoryGirl)Agile Web Development с Rails 4: Ошибка MiniTest для обновления действия в line_items_controller_test.rb
Ошибка (не провал) я получаю выглядит так:
Finished tests in 0.936959s, 26.6821 tests/s, 56.5660 assertions/s.
1) Error:
LineItemsControllerTest#test_should_update_line_item:
ActionController::ActionControllerError: Cannot redirect to nil!
app/controllers/line_items_controller.rb:54:in `block (2 levels) in update'
app/controllers/line_items_controller.rb:52:in `update'
test/controllers/line_items_controller_test.rb:38:in `block in <class:LineItemsControllerTest>'
25 tests, 53 assertions, 0 failures, 1 errors, 0 skips
Непонятно, почему я перенаправляю на нуль. Путь плохой? Или это объект в конце пути? И/или "другое"? Я не вижу ничего в самом контроллере, который выглядит как проблема (несмотря на то, что я включил код ниже), поэтому я подозреваю, что это имеет какое-то отношение к настройкам тестового файла или настроек. Я пробовал заполнять различные значения «фиктивный» (например, product_id: 55
) и «ссылочный» (например, product_id: products(:ruby).id
) в светильниках line_items.yml без успеха.
Я также пробовал разные вещи в рамках теста контроллера установки, например, ссылки на конкретные идентификаторы приборов в других типах приборов (товары и тележки), к которым относятся позиции (те же идеи, что и выше). Я попытался отредактировать тест обновления в ряде направлений, а также, в том числе пытаясь редирект в корзину ЦПО вместо line_items_path, такие как:
assert_redirected_to cart_path(assigns(:line_item).cart)
... вместо ...
assert_redirected_to line_item_path(assigns(:line_item))
также попытался варианты определения: Line_Item, которые я беру, чтобы быть обновленный объект, например:
patch :update, id: @line_item, line_item: { product_id: products(:ruby).id }
... вместо ...
patch :update, id: @line_item, line_item: { product_id: @line_item.product_id }
Что я считаю релевантным кодом, приведенным ниже. Любая помощь очень ценится!
line_items_controller.rb
class LineItemsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:create]
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
# GET /line_items
# GET /line_items.json
def index
@line_items = LineItem.all
end
# GET /line_items/1
# GET /line_items/1.json
def show
end
# GET /line_items/new
def new
@line_item = LineItem.new
end
# GET /line_items/1/edit
def edit
end
# POST /line_items
# POST /line_items.json
def create
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to @line_item.cart,
notice: 'Line item was successfully created.' }
format.json { render action: 'show',
status: :created, location: @line_item }
else
format.html { render action: 'new' }
format.json { render json: @line_item.errors,
status: :unprocessable_entity }
end
end
session[:count] = nil
end
# PATCH/PUT /line_items/1
# PATCH/PUT /line_items/1.json
def update
respond_to do |format|
if @line_item.update(line_item_params)
format.html { redirect_to @line_item.cart,
notice: 'Line item was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @line_item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /line_items/1
# DELETE /line_items/1.json
def destroy
@line_item.destroy
respond_to do |format|
format.html { redirect_to line_items_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_line_item
@line_item = LineItem.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def line_item_params
params.require(:line_item).permit(:product_id)
end
end
line_items_controller_test.rb
require 'test_helper'
class LineItemsControllerTest < ActionController::TestCase
setup do
@line_item = line_items(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:line_items)
end
test "should get new" do
get :new
assert_response :success
end
test "should create line_item" do
assert_difference('LineItem.count') do
post :create, product_id: products(:ruby).id
end
assert_redirected_to cart_path(assigns(:line_item).cart)
end
test "should show line_item" do
get :show, id: @line_item
assert_response :success
end
test "should get edit" do
get :edit, id: @line_item
assert_response :success
end
test "should update line_item" do
patch :update, id: @line_item, line_item: { product_id: @line_item.product_id }
assert_redirected_to line_item_path(assigns(:line_item))
end
test "should destroy line_item" do
assert_difference('LineItem.count', -1) do
delete :destroy, id: @line_item
end
assert_redirected_to line_items_path
end
end
line_items.yml
one:
product_id: #Trying values here doesn't seem to help.
cart_id: #Trying values here doesn't seem to help.
two:
product_id:
cart_id:
products.yml
one:
title: MyString
description: MyText
image_url: MyString
price: 9.99
two:
title: MyString
description: MyText
image_url: MyString
price: 9.99
ruby:
title: Programming Ruby 1.9
description:
Ruby is the fastest growing and most exicting dynamic
language out there. If you need to get working programs
delivered fast, you should add Ruby to your toolbox.
price: 49.50
image_url: ruby.png
three:
title: MyString
description: MyText
image_url: MyString
price: 9.99
тележки.YML
one: {}
# column: value
#
two: {}
# column: value
Спасибо за быстрый ответ! Ах, после первого чтения вашего ответа я был убежден, что это проблема ... тогда я попробовал это и ... ту же (ошибку) историю. – Ben