在 Rails 3.1 中使用 Rspec 和 Factory girl 测试嵌套资源控制器



我在user下有一个嵌套的资源专业。

我的routes.rb看起来像

  resources :users do
     resources :specialties do
     end
  end

我的工厂.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

前两个测试通过,但最后一个测试失败并显示错误消息

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

有没有人知道此错误意味着什么以及如何解决它?我查看了类似的帖子,在我的代码中找不到错误。提前谢谢。

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

specialty是一对多关系,应该是复数:specialties 。事实上,您的控制器中具有:

@specialties = @user.specialties

最新更新