2015-07-20 117 views
0

快速概要:爲什麼不能水豚找到.admin-edit類?水豚DOM橫向測試

因此,我建立了一個網站,其中有發佈和未發佈的文章,只有發佈的文章被客人看到,而管理員可以看到所有內容。登錄通過設計進行處理,一個簡單的erb表達式確定文章是否顯示或「發佈」。

我列出了有關我的文章控制器的索引操作的文章,並呈現了部分文章。

<% if article.published %> 
    <dl class="individual-article"> 
    <dt><%= article.title %> 
     <% if current_user.try(:admin) %> 
     | <span class="admin-edit"><%= link_to 'Edit', edit_article_path(article) %></span> 
    <% end %><br> 
    <span class="article-tags"> 
     <%= raw article.tags.map(&:name).map { |t| link_to t, tag_path(t) }.join(', ') %></span> 
    </dt> 
    <dd><%= truncate(article.body.html_safe, length: 200) %> 
     <%= link_to 'more', article_path(article) %> 
    </dd> 
    </dl> 
<% end %> 

這個按預期工作,但我無法正確測試它。特別是,如果用戶是管理員,那麼在期望找到「編輯」時返回false。

這裏是我的sign_in_spec:

require 'rails_helper' 

RSpec.describe "SignIns", type: :request do 

describe "the sign in path" do 
    let(:user)  { FactoryGirl.create(:user)  } 
    let(:admin)  { FactoryGirl.create(:admin)  } 
    let(:article)  { FactoryGirl.create(:article) } 
    let(:published) { FactoryGirl.create(:published) } 

    it "lets a valid user login and redirects to main page" do 
    visit '/users/sign_in' 
    fill_in 'user_email', :with => admin.email 
    fill_in 'user_password', :with => admin.password 
    click_button 'Log in' 
    expect(current_path).to eq '/' 
    expect(page).to have_css('span.admin-edit') 
    end 
end 

這裏是我的文章廠:

FactoryGirl.define do 
    factory :article do 
    title 'Title' 
    body 'Content' 

    factory :published do 
    published true 
    end 
end 

,這裏是我的用戶廠:

FactoryGirl.define do 

    factory :user do 
    email '[email protected]' 
    password 'password' 

    factory :admin do 
     admin true 
    end 
    end 
end 

以下是錯誤:

1) SignIns the sign in path lets a valid user login and redirects to main page 
Failure/Error: expect(page).to have_css('span.admin-edit') 
    expected #has_css?("span.admin-edit") to return true, got false 
# ./spec/requests/sign_ins_spec.rb:18:in `block (3 levels) in <top (required)>' 

我曾嘗試以下:

  1. 消除多餘的文章,如果rspec的曾與多個類的問題
  2. 更改have_css到have_selector並選擇錨標記
  3. 繪製出從整個DOM根html body ...
  4. 檢查它是否在規範之外工作,通過以管理員權限用戶手動登錄 - >它確實如此。
  5. 試圖刪除未發表vs發表文章的區別但仍然失敗。
  6. 嘗試刪除erb條件以檢查文章是否在視圖中發佈但仍然失敗。
  7. 嘗試確保它沒有通過ajax加載(在will_paginate中有備份)但失敗。

我在做什麼錯?

編輯

現在,如果我避免使用FactoryGirl導入工作:

@article = Article.create(title: 'Title', body: 'body', published: true) 

而不是

let(:published) { FactoryGirl.create(:published) } 

不知道爲什麼。

+0

您是否在click_button登錄後嘗試過'save_and_open_page'?你看到跨度? – forthowin

+0

是的,它沒有出現。奇怪的。 – user3162553

+0

我能想到的唯一的事情是它可能與兩個用戶使用同一封電子郵件有關,也許它默默地失敗了,因爲它不會重定向到主頁面,因此無法找到跨度。 – user3162553

回答

1

RSpec懶洋洋地分配let變量,所以當你顯示你的頁面時,既沒有發佈也沒有未發佈的文章。您需要使用let!before或以其他方式確保在顯示頁面之前創建對象。

+0

它的工作原理!不知道這是懶惰的分配。謝謝 :) – user3162553