2

ユーザーの下にネストされたリソースの専門分野があります。

私のroutes.rbは次のようになります

  resources :users do
     resources :specialties do
     end
  end

私のfactory.rbは次のようになります

Factory.define :user do |f|
  f.description { Populator.sentences(1..3) }
  f.experience { Populator.sentences(1..5) }
  f.tag_list { create_tags }
end

Factory.define :specialty do |f|
  f.association :user
  specialties = CategoryType.valuesForTest
  f.sequence(:category) { |i| specialties[i%specialties.length] }
  f.description { Populator.sentences(1..5) }
  f.rate 150.0
  f.position { Populator.sentences(1) }
  f.company { Populator.sentences(1) }
  f.tag_list { create_tags }
end

私のSpecialties_controller.rbは次のようになります

class SpecialtiesController < ApplicationController

def index
    @user = User.find(params[:user_id])
    @specialties = @user.specialties
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @specialties }
    end
  end

私のspecialties_controller_spec.rbは次のようになります

require 'spec_helper'

describe SpecialtiesController do
  render_views

  describe "GET 'index'" do
    before do
      @user = Factory.create(:user)
      @specialty = Factory.create(:specialty, :user => @user)
      @user.stub!(:specialty).and_return(@specialty)
      User.stub!(:find).and_return(@user)
    end

    def do_get
      get :index, :user_id => @user.id
    end

    it "should render index template" do
      do_get
      response.should render_template('index')
    end

    it "should find user with params[:user_id]" do
      User.should_receive(:find).with(@user.id.to_s).and_return(@user)
      do_get
    end

    it "should get user's specialties" do
       @user.should_receive(:specialty).and_return(@specialty)
       do_get
    end
   end
 end

最初の 2 つのテストは成功しますが、最後のテストは失敗し、エラー メッセージが表示されます。

Failure/Error: @user.should_receive(:specialty).and_return(@specialty)
       (#<User:0x007fe4913296a0>).specialty(any args)
           expected: 1 time
           received: 0 times

このエラーの意味と修正方法を知っている人はいますか? 同様の投稿を見てきましたが、コードにエラーが見つかりません。前もって感謝します。

4

1 に答える 1

1
@user.should_receive(:specialty).and_return(@specialty)

specialtyは 1 対多の関係であり、複数形にする必要があります: specialties. 実際、コントローラーには次のものがあります。

@specialties = @user.specialties
于 2012-06-12T21:13:15.410 に答える