【问题标题】:find method received two times while expected oncefind 方法收到两次,而预期一次
【发布时间】:2013-07-15 05:44:54
【问题描述】:

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

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

spec/controllers/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

我正在测试编辑操作。我对问题设定了期望,以在第一个示例中接收 find 并在第二个示例中接收存根 find 方法调用。我在第一个示例中遇到错误 我认为这两个例子并不完全相互隔离。

【问题讨论】:

  • 错误信息似乎与规范不符。首先,错误消息以“GET #edit”开头,而规范以“get edit”开头。其次,错误报告中的期望有一个with 子句,而规范没有。

标签: rspec ruby-on-rails-3.2


【解决方案1】:

你应该做一个 PUT 请求:

put :edit, id: question.id

【讨论】:

    猜你喜欢
    • 2017-07-15
    • 1970-01-01
    • 2013-06-16
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多