[英]rails namespaced controller test in rspec
我的规格总体上可以正常工作,但是当我尝试测试嵌套控制器时,出现一个奇怪的错误。 因此,此代码模式subject(:create_action) { xhr :post, :create, post_id: post.id, post_comment: attributes_for(:post_comment, post_id: post.id, user: @user) }
在我不兼容的控制器上正常工作嵌套,但是对于我的命名空间控制器,此处的测试it "saves the new task in the db
会引发以下错误:
1) Posts::PostCommentRepliesController when user is logged in POST create with valid attributes saves the new task in the db
Failure/Error: subject(:create_action) { xhr :post, :create, post_comment_id: post_comment.id, post: attributes_for(:post_comment_reply, post_comment: post_comment, user: @user) }
ArgumentError:
wrong number of arguments (4 for 0)
我应该怎么做才能使这项工作? 如您所见,我将我的post_comments_controller_spec.rb
放在specs/controllers/posts
文件夹中,并要求posts/post_comments_controller
,但这无济于事。
routes.rb
resources :posts do
resources :post_comments, only: [:create, :update, :destroy, :show], module: :posts
end
规格/控制器/帖子/post_comments_controller_spec.rb
require "rails_helper"
require "posts/post_comments_controller"
describe Posts::PostCommentsController do
describe "when user is logged in" do
before(:each) do
login_user
end
it "should have a current_user" do
expect(subject.current_user).to_not eq(nil)
end
describe "POST create" do
let!(:profile) { create(:profile, user: @user) }
let!(:post) { create(:post, user: @user) }
context "with valid attributes" do
subject(:create_action) { xhr :post, :create, post_id: post.id, post_comment: attributes_for(:post_comment, post_id: post.id, user: @user) }
it "saves the new task in the db" do
expect{ create_action }.to change{ PostComment.count }.by(1)
end
end
end
end
end
这是一个有点奇怪的错误。 总之,你let!(:post) { ... }
最后重写调用方法post
所使用发出一个POST请求的例子组。
发生这种情况的原因是,当您在describe
定义let
,RSpec会在给定的示例组中为您定义一个名称相同的方法 。
describe Post do
let(:post) { Post.new }
it "does something" do
post.do_something
end
end
xhr
方法 (以及get
, post
等)是从Rails本身进行测试的辅助方法。 RSpec的帮助程序包括此模块 ,因此可以在测试中使用。
describe PostController, type: :controller do
let(:comment) { Comment.new }
it "can post a comment thanks to Rails TestCase::Behaviour" do
post :create, comment
# xhr :post, ... under the covers calls for post method
end
end
因此,示例组对象有一个称为post的方法,当您创建let时,RSpec会在该组对象上创建一个具有相同名称的方法,从而覆盖原始的(并且非常需要)post方法。
describe PostController, type: :controller do
let(:post) { Post.new }
it "mixes up posts" do
post :create, post # post now refers to the variable, so this will cause an error
end
end
为了轻松解决此问题,我建议将let(:post)
命名为其他名称,例如new_post
。
describe PostController, type: :controller do
let(:new_post) { Post.new }
it "does not mix up posts" do
post :create, new_post # no more conflict
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.