1

私は2つのモデルを持っています:

class Solution < ActiveRecord::Base
  belongs_to :owner, :class_name => "User", :foreign_key => :user_id
end                  

class User < ActiveRecord::Base
  has_many :solutions
end

次のルーティングを使用します。

map.resources :users, :has_many => :solutions

ここにSolutionsControllerがあります:

class SolutionsController < ApplicationController
  before_filter :load_user

  def index
    @solutions = @user.solutions
  end

  private
    def load_user
      @user = User.find(params[:user_id]) unless params[:user_id].nil?
    end
end

index アクションのテストを書くのを手伝ってくれる人はいますか? これまでのところ、次のことを試しましたが、うまくいきません。

describe SolutionsController do
  before(:each) do
    @user = Factory.create(:user)
    @solutions = 7.times{Factory.build(:solution, :owner => @user)}
    @user.stub!(:solutions).and_return(@solutions)
  end

  it "should find all of the solutions owned by a user" do
    @user.should_receive(:solutions)
    get :index, :user_id => @user.id
  end
end

そして、次のエラーが表示されます。

Spec::Mocks::MockExpectationError in 'SolutionsController GET index, when the user owns the software he is viewing should find all of the solutions owned by a user'
#<User:0x000000041c53e0> expected :solutions with (any args) once, but received it 0 times

すべての助けを前もって感謝します。

ジョー

編集:

答えてくれてありがとう、別のエラーが発生していることを除いて、私はそれを受け入れました。

ソリューションをビルドする代わりに作成し、User.find のスタブを追加すると、次のエラーが表示されます。

NoMethodError in 'SolutionsController GET index, when the user owns the software he is viewing should find all of the solutions owned by a user'
undefined method `find' for #<Class:0x000000027e3668>    
4

2 に答える 2

2

それは、作成するのではなく、ソリューションを構築するためです。したがって、データベースにはありません。

作る

  before(:each) do
    @user = Factory.create(:user)
    @solutions = 7.times{Factory.create(:solution, :owner => @user)}
    @user.stub!(:solutions).and_return(@solutions)
  end

そして、ユーザーのインスタンスをモックしますが、インスタンス化できるユーザーの別のインスタンスがあります。モック User.find も追加する必要があります

  before(:each) do
    @user = Factory.create(:user)
    @solutions = 7.times{Factory.create(:solution, :owner => @user)}
    User.stub!(:find).with(@user.id).and_return(@user)
    @user.stub!(:solutions).and_return(@solutions)
  end
于 2010-03-28T17:43:40.830 に答える
0

パラメータから検索が行われると、実際のオブジェクトや整数ではなく文字列になるため、次の代わりに編集を理解しました。

User.stub!(:find).with(@user.id).and_return(@user)

必要だった

User.stub!(:find).with(@user.id.to_s).and_return(@user)

しかし、シンガラ、正しい方向に導いてくれてありがとう!

ジョー

于 2010-03-29T00:27:33.627 に答える