我正在跟随Rspec测试教程。尝试运行测试时出现语法错误。这是我的测试代码:
require 'rails_helper'
RSpec.describe CommentsController, type: :controller do
describe "comments#create action" do
it "should allow admins to create comments on posts" do
post = FactoryGirl.create(:post)
admin = FactoryGirl.create(:admin)
sign_in admin
post :create, params: { post_id: post.id, comment: { message: 'awesome post' } }
expect(response).to redirect_to root_path
expect(post.comments.length).to eq 1
expect(post.comments.first.message).to eq "awesome gram"
end
it "should require an admin to be logged in to comment on a post" do
post = FactoryGirl.create(:post)
post :create, params: { post_id: post.id, comment: { message: 'awesome post' } }
expect(response).to redirect_to new_admin_session_path
end
it "should return http status code of not found if the post isn't found" do
admin = FactoryGirl.create(:admin)
sign_in admin
post :create, params: { post_id: 'SUNSHINE', comment: { message: 'awesome post'} }
expect(response).to have_http_status :not_found
end
end
end
这是控制器:
class CommentsController < ApplicationController
before_action :authenticate_admin!, only: [:create]
def create
@post = Post.find_by_id(params[:post_id])
return render_not_found if @post.blank?
@post.comments.create(comment_params.merge(admin: current_admin))
redirect_to root_path
end
private
def render_not_found(status=:not_found)
render plain: "#{status.to_s.titleize} :(", status: status
end
def comment_params
params.require(:comment).permit(:message)
end
end
这是运行测试时的终端输出:
奇怪的是,当我评论产生错误的行时,测试按照预期运行,最后一次测试通过。我已经检查了测试文件以及描述相同问题的类似帖子,它看起来像语法是正确的。 Rails的新手如此宽恕新秀的错误。
答案 0 :(得分:1)
问题是你有一个名为post
的变量:
post = FactoryGirl.create(:post) # define `post` variable
post :create, params: ... # try to call `post` method
因此,在后续行中post
将引用变量,而不是post
方法。
解决方案1:重命名变量
my_post = FactoryGirl.create(:post)
post :create, params: { post_id: my_post.id, ... }
解决方案2:使用self.post
访问方法
post = FactoryGirl.create(:post)
self.post :create, params: { post_id: post.id, ... }
在irb
中复制问题:
def foo
"bar"
end
foo = "wat"
#=> "wat"
foo :hello
# SyntaxError: (irb):63: syntax error, unexpected ':', expecting end-of-input
# foo :hello
# ^
答案 1 :(得分:0)
我认为这与您定义名为post
的变量然后尝试调用Rspec
方法post
有关:
it "should require an admin to be logged in to comment on a post" do
post = FactoryGirl.create(:post)
post :create, params: { post_id: post.id, comment: { message: 'awesome post' } }
expect(response).to redirect_to new_admin_session_path
end
尝试重新命名:
调用Rspec
方法post
:
it "should require an admin to be logged in to comment on a post" do
message = FactoryGirl.create(:post)
post :create, params: { post_id: message.id, comment: { message: 'awesome post' } }
expect(response).to redirect_to new_admin_session_path
end