2015-06-19 17 views
0

我想鏈接我的people_controller.rb文件與我的index.erb文件,以便用戶可以點擊/ people頁面上的名稱並轉到通過people /:id路由的唯一頁面。這在瀏覽器中可以正常工作,但是應用程序一直未能通過我給出的spec測試。我在想我給出的spec文件是不正確的,實際上並沒有測試鏈接的存在。使用rspec來測試一個網址是否存在一個sinatra應用程序

這是我people_controller.rb文件:

get "/people" do 
    @people = Person.all 

    erb :"/people/index" 
end 

get "/people/:id" do 
    @person = Person.find(params[:id]) 
    birthdate_string = @person.birthdate.strftime("%m%d%Y") 
    birth_path_num = Person.get_birth_path_num(birthdate_string) 
    @message = Person.get_message(birth_path_num) 

    erb :"/people/show" 
end 

這是我index.erb文件:

<h1>People</h1> 

<table> 

    <thead> 
     <th>Name</th> 
     <th>Birthdate</th> 
    </thead> 

    <tbody> 
     <% @people.each do |person| %> 
      <tr> 
       <td> 
        <a href="<%="people/#{person.id}" %>"> 
         <%= "#{person.first_name} #{person.last_name}" %> 
        </a> 
       </td> 
       <td> 
        <%= "#{person.birthdate}" %> 
       </td> 
      </tr> 
     <% end %> 
    </tbody> 

</table> 

這是我的規格文件:

require 'spec_helper' 

describe "Our Person Index Route" do 
    include SpecHelper 

    before (:all) do 
    @person = Person.create(first_name: "Miss", last_name: "Piggy", birthdate: DateTime.now - 40.years) 
    end 

    after (:all) do 
    @person.delete 
    end 

    it "displays a link to a person's show page on the index view" do 
    get("/people") 
    expect(last_response.body.include?("/people/#{@person.id}")).to be(true) 
    end 
end 

這是失敗消息當我嘗試使用spec文件運行rspec時出現錯誤消息:

Failure/Error: expect(last_response.body.include?("/people/#{@person.id}")).to be(true) 
expected true 
got false 
# ./spec/people_show_link_spec.rb:16:in 'block (2 levels) in <top (required)>' 

是期望方法實際上檢查鏈接的存在或只檢查在人員頁面上是否有文本字符串「/people/#{@person.id}」?它不應該以某種方式包含「一個href」(或其他一些指示鏈接的關鍵字),如果它實際上檢查鏈接?

回答

0

它只檢查是否有文本字符串「/people/#{@person.id}」。

一個更好的預期可能是:

expect(page).to have_css "a[href='/people/#{@person.id}']" 

expect(page).to have_link "#{person.first_name} #{person.last_name}" 
+0

指令終端說,網頁是一個未定義的局部變量。 @page不起作用,因爲它沒有在任何文件中定義。你有一個doc或資源引用.to has_css或.to has_link方法嗎?我沒有看到他們參考rspec。我想我可能需要以某種方式使用重定向方法,但我不確定。 – user4992261

+0

我應該注意到我沒有水豚。我認爲.to_css和.to_have鏈接是水豚的方法,但我只有Sinatra。 – user4992261

+0

水豚與Sinatra合作。如果你想做一些事情,比如檢查HTML節點,那麼你可能想要使用它。您可能需要配置RSpec以同時使用機架測試和水豚: –

相關問題