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)
pla*_*mbo 19
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为我工作.
在指定帮助程序时可以使用此语法
假设这是你的帮手
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)
当您描述它们时,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的解决方案更好.
| 归档时间: |
|
| 查看次数: |
14105 次 |
| 最近记录: |