ruby-on-rails - 测试 'save' 函数在传递无效数据时失败。 ( ruby Rspec)

标签 ruby-on-rails ruby rspec

我正在从事一个在“项目”模型中具有以下验证标准的项目:

validates :project_name,
            presence: true,
            format: { with: /\A[a-zA-Z\s_-]+\z/,
                      message: 'allows letters, spaces, underscores, and hyphens' }
  validates :jira_id,
            uniqueness: true,
            presence: true,
            format: { with: /\A[A-Z]+-[0-9]+\z/,
                      message: 'allows capitalized letters followed by a hyphen and numbers' }
  validates :capacity,
            presence: true,
            numericality: { only_integer: true, greater_than_or_equal_to: 0 }
  validates :openings,
            presence: true,
            numericality: { only_integer: true, greater_than_or_equal_to: 0 }

  validates_format_of :last_status_change_dt,
                      with: /\d{4}-\d{2}-\d{2}/,
                      message: 'must be formatted as YYYY-MM-DD',
                      on: :save

  validates_presence_of :last_status_change_dt

projects_controller:

def create
    ActiveRecord::Base.transaction do
      parameters = project_params.dup
      parameters[:language_id] = get_language_id(params[:language_name]) if parameters[:language_id].nil?
      @project = Project.new(parameters)
      if @project.save
        render json: @project, status: :created, location: @project
      else
        render json: @project.errors, status: :not_acceptable
        raise ActiveRecord::Rollback
      end
    end
  rescue ActiveRecord::ActiveRecordError
    render json: { text: 'Project was not created' }, status: :internal_server_error
  end

在规范文件中,使用了 FactoryBot 构建和创建函数。

在目前的测试中,验证依赖于项目模型,但我想测试保存功能。如何模拟保存功能失败?

最佳答案

您可以使用 allow_any_instance_of ,但这有点重锤。相反,制作一个 double 和 mock Project.new 来返回它。

context 'Project#save raises ActiveRecord::ActiveRecordError' do
  let(:project) {
    # Set up the double to fail on save.
    instance_double("Project").tap { |project|
      allow(project).to receive(:save).and_raise(ActiveRecord::ActiveRecordError)
    }
  }

  before {
    # Set up Project.new to return the double
    allow(Project).to receive(:new).and_return(project)
  }
end

请注意,save 引发 ActiveRecord::ActiveRecordError 是很不寻常的,如果它做了一些非常不寻常的事情就出错了。您通常不会在 Controller 中拯救它。

关于ruby-on-rails - 测试 'save' 函数在传递无效数据时失败。 ( ruby Rspec),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66391170/

相关文章:

ruby-on-rails - rails : is Passenger Standalone suitable for production deployment?

ruby-on-rails - 验证对象时,Ruby on Rails 如何执行不带任何参数的 lambda?

ruby - 有趣的错误?在预装 Ruby (1.8.7) 的操作系统中

mysql - Rails 4/postgresql 索引 - 我应该使用可以有无限多个值的日期时间列作为索引过滤器吗?

ruby-on-rails - rails 4.0 中的多个 'root to' 路由

ruby-on-rails - Rails,从 NEW 重定向到 CREATE

ruby-on-rails - 如何使用 Rails + Bootstrap + formtastic_bootstrap 聚焦表单输入字段

ruby-on-rails - 在 RSpec Capybara 测试中,您如何 stub 您自己的应用程序的 API?

ruby-on-rails - RSpec 列出所有挂起的例子

ruby-on-rails - 如何让 RSpec 测试子目录中的 Controller ?