mr_*_*cle 1 ruby rspec ruby-on-rails
我正在尝试为我的嵌套注释控制器测试'destroy'操作.
用户模型has_many :comments, dependent: :destroy
电影模型has_many :comments, dependent: :destroy
评论模型belongs_to :user and :movie
这是我的评论控制器
def create
@comment = @movie.comments.new(comment_params.merge(user: current_user))
if @comment.save
flash[:notice] = 'Comment successfully added'
redirect_to @movie
else
flash.now[:alert] = 'You can only have one comment per movie'
render 'movies/show'
end
end
def destroy
@comment = @movie.comments.find(params[:id])
if @comment.destroy
flash[:notice] = 'Comment successfully deleted'
else
flash[:alert] = 'You are not the author of this comment'
end
redirect_to @movie
end
private
def comment_params
params.require(:comment).permit(:body)
end
def set_movie
@movie = Movie.find(params[:movie_id])
end
Run Code Online (Sandbox Code Playgroud)
当然也有before_action :set_movie, only: %i[create destroy]
顶部.
这是我的规格,我正在使用FactoryBot,所有工厂在其他示例中工作正常,所以我认为这个问题在其他地方.
describe "DELETE #destroy" do
let(:user) { FactoryBot.create(:user) }
let(:movie) { FactoryBot.create(:movie) }
before do
sign_in(user)
end
it "deletes comment" do
FactoryBot.create(:comment, movie: movie, user: user)
expect do
delete :destroy, params { movie_id: movie.id }
end.to change(Comment, :count).by(-1)
expect(response).to be_successful
expect(response).to have_http_status(:redirect)
end
end
Run Code Online (Sandbox Code Playgroud)
我有一个错误,ActionController::UrlGenerationError: No route matches {:action=>"destroy", :controller=>"comments", :movie_id=>1}
我认为我的规范中的地址破坏行为是错误的,但如何以一种好的方式定义它?
您需要指定要删除的注释的ID:
it "deletes comment" do
comment = FactoryBot.create(:comment, movie: movie, user: user)
expect do
delete :destroy, params { id: comment.id, movie_id: movie.id }
end.to change(Comment, :count).by(-1)
# ...
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
626 次 |
最近记录: |