4

したがって、パフォーマンス上の理由から、SQLクエリを使用せずに達成する必要があることを達成する必要があるメソッドのテストを作成しています。私が知る必要があるのは、何をスタブするかだけだと思っています。

describe SomeModel do
  describe 'a_getter_method' do
    it 'should not touch the database' do
      thing = SomeModel.create

      something_inside_rails.should_not_receive(:a_method_querying_the_database)

      thing.a_getter_method
    end
  end
end

編集:より具体的な例を提供するには:

class Publication << ActiveRecord::Base
end
class Book << Publication
end
class Magazine << Publication
end

class Student << ActiveRecord::Base
  has_many :publications

  def publications_of_type(type)
    #this is the method I am trying to test.  
    #The test should show that when I do the following, the database is queried.

    self.publications.find_all_by_type(type)
  end
end


describe Student do
  describe "publications_of_type" do
    it 'should not touch the database' do
       Student.create()
       student = Student.first(:include => :publications)
       #the publications relationship is already loaded, so no need to touch the DB

       lambda {
         student.publications_of_type(:magazine)
       }.should_not touch_the_database
    end
  end
end

したがって、この例では、railsの'find_all_by'メソッドがSQLに依存しているため、テストは失敗するはずです。

4

5 に答える 5

7

SomeModel.should_not_receive(:connection)それをする必要があります。

于 2012-11-16T14:24:30.147 に答える
0

SomeModel.createのインスタンスを作成SomeModelしてデータベースに保存し、作成したオブジェクトを返します。

getter メソッドがデータベースにアクセスしないようにします? Rails では、アソシエーションの取得のみがデータベースにヒットし、それらが最初に呼び出されたときにのみヒットします。

データベースにヒットすると「疑う」ゲッターメソッドの特定の実装がある場合、テストは簡単だと思いますか、それとも将来の実装から保護していますか?

おそらく最も簡単な方法はSomeModel.build、 を実行してからテストを実行することです。はbuild、インスタンスをデータベースに保存せずに作成します。ゲッターが機能する場合は、データベースにヒットしていないことは確かです (コードによっては、そこに何もないはずなので、実際にテストしているゲッターについての手がかりなしに言うのは少し難しいです)。

特定の getter メソッドをテストしていて、より関連性の高い回答が必要な場合は、コードを提供してください。

于 2012-11-16T14:15:15.890 に答える