2017-02-20 101 views
2

我用一個簡單的測試軌測試rspec的水豚have_css不匹配

require "rails_helper" 

RSpec.feature "Home page", :type => :feature do 
scenario "When a user visit it" do 
    visit "/" 
    expect(page).to have_css('article', count: 10) 
end 
end 

在我有這樣的代碼視圖掙扎

<% @articles.each do |article| %> 
    <article> 
    <header> <%= article.title%> </header> 
    <div class="content-summary"> <%= article.body %> </div> 
    </article> 
    <hr/> 
<% end %> 

當我運行測試,我得到

Failure/Error: expect(page).to have_css('article', count: 10) 
    expected to find css "article" 10 times but there were no matches 

我運行服務器,我可以看到存在10個文章標籤。

當我改變了看法這個

<% 10.times do %> 
    <article> 
    <header> </header> 
    <div class="content-summary"> </div> 
    </article> 
    <hr/> 
<% end %> 

測試通過

請幫我

+0

請問您能否顯示您的整個測試文件? –

+0

@ Slava.K我添加了整個測試文件 –

+3

在您的測試中沒有創建任何文章。你需要在'before'塊中創建一些。當你運行服務器時,它使用'開發'數據庫,並且測試套件使用'test'一個 –

回答

1

的Rails爲每個環境的單獨的數據庫。本地服務器在默認情況下以development模式運行,因此連接到app_name_development數據庫。但是,RSpec在test環境中運行測試並使用app_name_test數據庫。這就是爲什麼運行服務器時看到的文章在RSpec測試中不可用。

測試需要手動設置數據。如果您正在使用RSpec,那麼我假設您也安裝了FactoryGirl。在這種情況下,測試應該看起來像這樣:

require "rails_helper" 

RSpec.feature "Home page", :type => :feature do 
    let!(:articles) { create_list(:article, 10) } 

    scenario "When a user visit it" do 
    visit "/" 
    expect(page).to have_css('article', count: 10) 
    end 
end