Rspec和测试实例方法

时间:2013-04-18 15:55:26

标签: ruby-on-rails rspec tdd

这是我的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

1 个答案:

答案 0 :(得分:1)

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

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

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