[英]Rspec and testing instance methods
Here is my rspec
file: 这是我的
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
Here is my Classroom Factory
: 这是我的
Classroom Factory
:
FactoryGirl.define do
factory :classroom do
name "Hello World"
active true
trait :archive do
active false
end
end
end
When the instance method test runs above, I receive the following error: stubbed models are not allowed to access the database
当实例方法测试在上面运行时,我收到以下错误:
stubbed models are not allowed to access the database
I understand why this is happening (but my lack of test knowledge/being a newb to testing) but can't figure out how to stub out the model so that it doesn't hit the database 我知道为什么会发生这种情况(但我缺乏测试知识/正在测试中的新手),但无法弄清楚如何对模型进行存根处理,以使其不会影响数据库
Working Rspec Tests: 工作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
Your archive!
您的
archive!
method is trying to save the model to the database. 方法正在尝试将模型保存到数据库。 And since you created it as a stubbed model, it doesn't know how to do this.
而且由于您将其创建为存根模型,因此它不知道如何执行此操作。 You have 2 possible solutions for this:
您有2种可能的解决方案:
archive
, don't save it to the database, and call that method in your spec instead. archive
,不要将其保存到数据库中,而是在您的规范中调用该方法。 Thoughtbot provides a good example of stubbing dependencies here . Thoughtbot提供了一个在此处存根依赖的好例子。 The subject under test (
OrderProcessor
) is a bona fide object, while the items passed through it are stubbed for efficiency. 被测试的对象(
OrderProcessor
)是一个真实的对象,而通过它的项目为了提高效率而被存根。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.