找到方法收到两次,而预期一次

时间:2013-07-14 21:09:23

标签: rspec ruby-on-rails-3.2

我在编写一些规范时遇到错误

QuestionsController GET #edit finds question to edit
     Failure/Error: Question.should_receive(:find).with("#{question.id}").and_return(question)
   (<Question(id: integer, title: string, body: text, created_at: datetime, updated_at: datetime, user_id: integer, up_votes: integer, down_votes: integer) (class)>).find("9")
       expected: 1 time
       received: 2 times

class QuestionsController < ApplicationController
  def edit
    @question = Question.find(params[:id])
  end
end

规格/控制器/ questions_spec.rb

  describe QuestionsController do
    describe 'get edit' do
      it 'finds question to edit' do
        question = create(:question)
        user = create(:user)
        sign_in user
        Question.should_receive(:find).and_return question
        get :edit, :id => question.id
      end
      it 'renders edit template' do 
        question = create(:question)
        user = create(:user)
        sign_in user
        Question.stub(:find).and_return question
        get :edit, :id => question.id
        expect(responce).to render_template 'edit'
      end
    end
  end

我使用Rspec,Factory Girl,database_cleaner,Postgres

spec_helper中的database_cleaner配置

  config.before(:suite) do
    DatabaseCleaner.clean_with :truncation
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each) do |group|
    # The strategy needs to be set before we call DatabaseCleaner.start
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
  config.use_transactional_fixtures = false

我正在测试编辑操作。我在第一个例子中设置了对Question的期望,在第二个例子中设置了stub find方法调用。我在第一个例子中收到错误 我认为这两个例子并没有完全相互隔离。

1 个答案:

答案 0 :(得分:1)

你应该做一个PUT请求:

put :edit, id: question.id