簡體   English   中英

RSpec中的Rails命名空間控制器測試

[英]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方法 (以及getpost等)是從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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM