使用rspec测试sinatra应用程序存在的URL

时间:2015-06-19 15:58:28

标签: ruby activerecord rspec routes sinatra

我正在尝试将我的people_controller.rb文件与index.erb文件链接,以便用户可以点击/ people页面中的名称,然后通过people /:id路由转到唯一页面。这适用于浏览器,但应用程序仍然无法通过我给出的规范测试。我认为我给出的spec文件不正确,实际上并没有测试链接是否存在。

这是我的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>

这是我的spec文件:

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}”?如果实际检查链接,它不应该以某种方式包含“a href”(或指示链接的其他关键字)吗?

1 个答案:

答案 0 :(得分:0)

它只检查是否有文本字符串&#34; / people /#{@ person.id}&#34;。

更好的期望可能是:

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

expect( page ).to have_link "#{person.first_name} #{person.last_name}"
相关问题