使用Ruby on Rails和RSpec编写助手规范

TK.*_*TK. 23 ruby bdd rspec ruby-on-rails

我一直在为控制器和模型编写规范,但我从未编写过帮助规范.我不知道我从哪里开始.

我有以下片段 application_helper.rb

  def title(page_title)
    content_for(:title) { page_title }
  end
Run Code Online (Sandbox Code Playgroud)
  • 我该如何在代码上编写帮助程序规范?
  • 此外,如果有任何开源Rails应用程序显示良好的帮助测试/规格,请告诉我.

pla*_*mbo 19

来自Helper规范rspec-rails文档:

Helper规范存在于spec/helpers中,并混合在ActionView :: TestCase :: Behavior中.

提供一个辅助对象,它与指定的辅助模块以及ApplicationHelper(如果存在)混合在一起.

require 'spec_helper'
describe ApplicationHelper do
  describe "#title" do
    it "displays the title" do
      # helper is an instance of ActionView::Base configured with the
      # ApplicationHelper and all of Rails' built-in helpers
      expect(helper.title).to match /Some Title/
    end
  end 
end
Run Code Online (Sandbox Code Playgroud)


vip*_*phe 10

也可以在测试类中包含您的帮助程序,如下所示:

 describe ApplicationHelper do
   helper ApplicationHelper

   it "should work" do
     my_helper_method("xyz").should == "result for xyz"
   end
 end
Run Code Online (Sandbox Code Playgroud)

用Rails 3为我工作.


Fab*_*bio 9

在指定帮助程序时可以使用此语法

假设这是你的帮手

module ApplicationHelper
  def page_title
    @title || nil
  end
end
Run Code Online (Sandbox Code Playgroud)

然后你可以用这种语法来规范它

require "spec_helper"

describe ApplicationHelper do
  describe "#page_title" do
    it "returns the instance variable" do
      assign(:title, "My Title")
      helper.page_title.should eql("My Title")
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


mak*_*oid 7

当您描述它们时,RSpec应该自动从您的rails环境加载类和模块,因此有效的帮助程序规范可能是:

#deleted
Run Code Online (Sandbox Code Playgroud)

但请记住,bdd不会测试每个方法,而是测试应用程序的行为.

编辑:

正如@Ken所说,我的规格不正确,这绝对是错误的做法.所以我推出了一个Request规范解决方案,我更喜欢Helper规范.

# inside your helper
def title=(page_title)
  content_for(:title) { page_title }
end

# views/resource/index.html.erb
<% title = "foo" %>

# views/layouts/application.html.erb
<%= yield :title %>

# request spec
require 'spec_helper'

describe YourResource do
  it "should output content for title"
    get "/resource"
    response.body.should =~ /<title>foo<\/title>/
  end
end
Run Code Online (Sandbox Code Playgroud)

否则,如果你只想测试帮助行为(因为它很关键或因为你没有任何视图)@ Ken的解决方案更好.

  • 由于content_for返回nil,因此测试不多.你应该渲染一个页面,assert_select"title"包含你所期望的. (4认同)