【问题标题】:Rspec and testing instance methodsRspec 和测试实例方法
【发布时间】:2013-04-18 15:55:25
【问题描述】:

这是我的rspec 文件:

require 'spec_helper'

describe Classroom, focus: true do

  describe "associations" do
    it { should belong_to(:user) }
  end

  describe "validations" do
    it { should validate_presence_of(:user) }
  end

  describe "instance methods" do

    describe "archive!" do
      before(:each) do
        @classroom = build_stubbed(:classroom)
      end

      context "when a classroom is active" do
        it "should mark classroom as inactive" do
          @classroom.archive!
          @classroom.active.should_be == false
        end
      end

    end

  end

end

这是我的Classroom Factory:

FactoryGirl.define do

  factory :classroom do
    name "Hello World"
    active true

    trait :archive do
      active false
    end
  end

end

上面运行实例方法测试时,收到如下错误:stubbed models are not allowed to access the database

我明白为什么会发生这种情况(但我缺乏测试知识/是测试新手),但不知道如何存根模型以使其不会进入数据库

工作 Rspec 测试:

require 'spec_helper'

describe Classroom, focus: true do

  let(:classroom) { build(:classroom) }

  describe "associations" do
    it { should belong_to(:user) }
  end

  describe "validations" do
    it { should validate_presence_of(:user) }
  end

  describe "instance methods" do

    describe "archive!" do

      context "when a classroom is active" do
        it "should mark classroom as inactive" do
          classroom.archive!
          classroom.active == false
        end
      end

    end

  end

end

【问题讨论】:

    标签: ruby-on-rails rspec tdd


    【解决方案1】:

    您的archive! 方法正在尝试将模型保存到数据库中。而且由于您将其创建为存根模型,因此它不知道如何执行此操作。您有两种可能的解决方案:

    • 将您的方法更改为archive,不要将其保存到数据库中,而是在您的规范中调用该方法。
    • 不要在测试中使用存根模型。

    Thoughtbot 提供了一个很好的存根依赖关系示例here。被测对象 (OrderProcessor) 是一个真正的对象,而通过它的项目被存根以提高效率。

    【讨论】:

    • 你能举个例子吗?在编写 TDD 时我完全迷失了
    • @dennismonsewicz:已更新 - 例如,请参见链接。在您的情况下,将build_stubbed 更改为build。如果你创建一个名为active 的特征并使用build(:classroom, :active)
    • 非常感谢您的帮助!我正在发布我在上面提出的内容
    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多