簡體   English   中英

如何模擬不存在的ActiveRecord模型以測試可安裝Rails的引擎

[英]How to mock a nonexistent ActiveRecord model for testing a Rails mountable engine

我花了很長的時間試圖找到一種解決方案,該方案如何模擬關聯的ActiveRecord模型,但幾乎一無所獲。

我正在遵循http://guides.rubyonrails.org/engines.html#testing-an-engine來構建一個簡單的可安裝引擎。 我很好奇您如何在這種情況下進行測試,如何模擬僅在將來的應用程序中存在的關聯ActiveRecord模型?

例如,如何編碼測試用例才能使“ post = Post.create!valid_attribute”通過?

在post.rb中:

attr_accessor :author_name
belongs_to :author, class_name: Blorgh.author_class

before_save :set_author

private
  def set_author
    self.author = Blorgh.author_class.find_or_create_by(name: author_name)
  end

在測試用例中:

  it "assigns all posts as @posts" do
    //how to do here?
    post = Post.create! valid_attributes

    get :index, {use_route: :blorgh}, valid_session
    assigns(:posts).should eq([post])
  end

錯誤:

  Failure/Error: post = Post.create! valid_attributes
  NoMethodError:
  undefined method `find_or_create_by' for nil:NilClass

blorg \\ lib目錄中的blorg.rb

  module Blorgh4mRspect
    mattr_accessor :author_class    
    def self.author_class
      @@author_class.constantize
    end
  end

您是否要繼續引用Blorgh.author_class抽象而不是對User類的硬編碼引用?

def set_author
  self.author = Blorgh.author_class.constantize.find_or_create_by(name: author_name)
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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