我想测试注释控制器,动作创建,但我不知道怎么做 . comments_controller
class CommentsController < ApplicationController
def create
@hotel = Hotel.find(params[:hotel_id])
@comment = @hotel.comments.new(comment_params)
@comment.user_id = current_user.id
@comment.save
redirect_to @hotel
end
private
def comment_params
params.require(:comment).permit(:user_id, :body, :hotel_id)
end
end
routes.rb
resources :hotels do
resources :comments
get 'list', on: :collection
post 'comment'
end
comments_controller_spec.rb
require 'rails_helper'
describe CommentsController do
login_user
describe 'POST create' do
it 'create a new comment with valid attributes' do
expect{
comment_attr = attributes_for(:comment)
post :create, comment: comment_attr
}.to change(Comment,:count).by(1)
end
it 'redirects to the new comment' do
comment_attr = attributes_for(:comment)
post :create, comment: comment_attr
expect(response).to redirect_to hotels_path(hotel)
end
end
end
factories.rb
FactoryGirl.define do
factory :user do |user|
user.email { Faker::Internet.email }
user.password 'password'
user.password_confirmation 'password'
end
factory :hotel do |hotel|
hotel.title 'Hotel'
hotel.description 'This is a some description for hotel'
hotel.breakfast true
hotel.price 20500
hotel.address { create(:address) }
hotel.user { create(:user) }
hotel.avatar { fixture_file_upload(Rails.root + 'spec/fixtures/images/example.jpg', "image/jpg") }
end
factory :comment do |comment|
comment.body 'This is a some comment ^_^'
comment.user { create(:user) }
comment.hotel { create(:hotel) }
end
factory :address do |address|
address.country { Faker::Address.country }
address.state { Faker::Address.state }
address.city { Faker::Address.city }
address.street { Faker::Address.street_name }
end
end
但我有这个错误:
1)CommentsController POST create使用有效属性创建一个新注释失败/错误:post:create,comment:comment_attr ActionController :: UrlGenerationError:没有路由匹配{:comment => {:body =>“这是一些注释^ _ ^“,:user =>”5“,:hotel =>”1“} ,: controller =>”comments“,:action =>”create“}# . / spec / control / comment_controller_spec.rb:10:in阻止(4级)在<top(必要)>'# . / spec / control /comments_controller_spec.rb:8:inblock(3级)中'2)CommentsController POST创建重定向到新注释失败/错误:post:create ,comment:comment_attr ActionController :: UrlGenerationError:没有路由匹配{:comment => {:body =>“这是一些注释^ _ ^”,:user =>“5”,:hotel =>“1”}, :controller =>“comments”,:action =>“create”}# . / spec / control /comments_controller_spec.rb:16:在`block(3 levels)in'
1 回答
我认为你的主要问题是你发送已经创建的对象的动作
Rails解析params并获取记录的
id
并尝试查找member
路由 . 看起来您想测试是否会从控制器中的params创建一个新的Comment . 它是嵌套资源,所以你应该发送hotel_id
以及尝试发送令我困惑的另一件事是路线中的
post 'comment', only: :create
. 我从未见过only
的选项only
- 通常它用于资源 .