【问题标题】:Nested RSpec Tests嵌套 RSpec 测试
【发布时间】:2014-01-03 18:35:11
【问题描述】:

我正在关注 Michael Hartl 的教程,但遇到了以下我无法理解的代码。

  describe "index" do
    let(:user) { FactoryGirl.create(:user) }
    before(:each) do
      sign_in user
      visit users_path
    end

    it { should have_title('All users') }
    it { should have_content('All users') }

    describe "pagination" do

      before(:all) { 30.times { FactoryGirl.create(:user) } }
      after(:all)  { User.delete_all }

      it { should have_selector('div.pagination') }

      it "should list each user" do
        User.paginate(page: 1).each do |user|
          expect(page).to have_selector('li', text: user.name)
        end
      end
    end
  end

我的问题是: 这是一个嵌套测试,其中分页测试块在索引测试块内运行?换句话说,测试流程的顺序:

  1. before(:each) 外层登录用户和访问用户路径执行
  2. 然后执行 30.times { FactoryGirl.create(:user) 的内部块
  3. 然后它的内部块 { should have_selector('div.pagination') } 被执行
  4. 然后执行expect(page).to have_selector('li', text: user.name)的内部块

谢谢

【问题讨论】:

    标签: ruby testing rspec nested


    【解决方案1】:

    这是上述测试的流程:

    before(:each) 块在以下各项之前执行:

    it { should have_title('All users') }
    it { should have_content('All users') }
    

    然后,再次执行before(:each),接着是describe block,执行:

    before(:all) { 30.times { FactoryGirl.create(:user) } }
    
    it { should have_selector('div.pagination') }
    
    it "should list each user" do
      User.paginate(page: 1).each do |user|
        expect(page).to have_selector('li', text: user.name)
      end
    end
    

    最后,after(:all) { User.delete_all } 被执行。

    我希望这有助于解释流程。

    【讨论】:

    • 如果 Pagination 块不是嵌套而是与 Index 块分开似乎更有意义。换句话说,为分页测试编写一个独立的登录用户和访问用户块。
    • 为什么?只有当您访问 index 并且您有足够的用户进行分页时,您才会进行分页...
    • 我想是的。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    相关资源
    最近更新 更多