Kri*_*ris 31 bdd rspec ruby-on-rails fixtures
我是新手使用RSpec在使用MySQL数据库的Rails应用程序中编写测试.我已经定义了我的灯具,并在我的规格中加载它们如下:
before(:all) do
  fixtures :student
end
Run Code Online (Sandbox Code Playgroud)
这个声明是否在学生表中保存我的灯具中定义的数据,或者只是在测试运行时将数据加载到表中,并在运行所有测试后将其从表中删除?
inf*_*sed 22
如果您想使用RSpec的灯具,请在describe块中指定您的灯具,而不是在之前的块中:
describe StudentsController do
  fixtures :students
  before do
    # more test setup
  end
end
Run Code Online (Sandbox Code Playgroud)
您的学生装备将被加载到学生表中,然后在每次测试结束时使用数据库事务回滚.
首先:你不能fixtures在:all/ :context/中使用方法:suite hook.不要试图在这些钩子中使用固定装置(如post(:my_post)).
您可以仅在describe/context块中准备灯具,如之前的Infuse写入.
呼叫
fixtures :students, :teachers
Run Code Online (Sandbox Code Playgroud)
不要将任何数据加载到DB中!只是准备辅助方法students和teachers.当您第一次尝试访问它们时,需要的记录会被懒散地加载.就在之前
dan=students(:dan) 
Run Code Online (Sandbox Code Playgroud)
这将加载学生和老师的delete all from table + insert fixtures方式.
所以如果你准备一些学生在之前(:context)钩子,他们现在就会走了!
在测试套件中只插入一次记录.
来自灯具的记录不会在测试套件的末尾删除.它们将被删除并重新插入到下一个测试套件运行中.
例:
 #students.yml
   dan:
     name: Dan 
   paul:
     name: Paul
 #teachers.yml
    snape:
      name: Severus
describe Student do
  fixtures :students, :teachers
  before(:context) do
    @james=Student.create!(name: "James")
  end
  it "have name" do
   expect(Student.find(@james.id).to be_present
   expect(Student.count).to eq 1
   expect(Teacher.count).to eq 0
   students(:dan)
   expect(Student.find_by_name(@james.name).to be_blank
   expect(Student.count).to eq 2
   expect(Teacher.count).to eq 1
  end
end
#but when fixtures are in DB (after first call), all works as expected (by me)
describe Teacher do
  fixtures :teachers #was loade in previous tests
  before(:context) do
    @james=Student.create!(name: "James")
    @thomas=Teacher.create!(name: "Thomas")
  end
  it "have name" do
   expect(Teacher.find(@thomas.id).to be_present
   expect(Student.count).to eq 3 # :dan, :paul, @james
   expect(Teacher.count).to eq 2 # :snape, @thomas
   students(:dan)
   expect(Teacher.find_by_name(@thomas.name).to be_present
   expect(Student.count).to eq 3
   expect(Teacher.count).to eq 2
  end
end
Run Code Online (Sandbox Code Playgroud)
上述测试中的所有期望都会过去
如果这些测试再次运行(在下一个套件中)并按此顺序运行,则超出预期
 expect(Student.count).to eq 1
Run Code Online (Sandbox Code Playgroud)
将不会满足!将有3名学生(:dan,:paul和全新的@james).所有这些都将被删除之前students(:dan)和之后:paul和:dan将再次插入.
before(:all)保留准确的数据,因为它被加载/创建一次。你做你的事情,并在测试结束时它保留下来。这就是为什么bui的链接必须after(:all)破坏或使用before(:each); @var.reload!;end才能从之前的测试中获取最新的数据。我可以看到在嵌套 rspec 描述块中使用这种方法。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           27568 次  |  
        
|   最近记录:  |