2014-09-01 95 views
2

我想測試我的application/layout.html.erb標題標籤:RSpec的查看測試和content_for:標題

<title><%= content_for?(:title) ? yield(:title) : "Foo Bar" %></title> 

但我發現沒有辦法設置標題變量:

it "should show a title" do 
    # NameError: `title' is not allowed as an instance variable name 
    #view.instance_variable_set(:title, 'Test Title') 

    # Deprecation error 
    # view.stub(:title) { 'Test Title' } 

    # Fail: 
    # allow(view).to receive(:title) { 'Test Title' } 
    # view.content_for(:title) { 'Test Title' } 
    # assign(:title, 'Test Title') 
    # helper.stub(:content_for).with(:title).and_return('Test Title') 

    render 

    expect(rendered).to have_title('Test Title') 
end 

我使用Rails 4.1.4,rspec-rails 3.0.2,水豚2.4.1。有什麼建議麼?

+0

這是在爲您的操作的視圖或佈局的規範呢?查看規範不會呈現其佈局。如果這已經*在您的佈局規範'view.content_for(:title){'測試標題'}',應該是你需要的所有... – alol 2014-09-04 12:37:26

回答

5

你可以做這樣的事情

view.instance_variable_get("@view_flow").set(:title,"Test Title") 
render 
expect(rendered).to have_title('Test Title') 
0

如果有人需要與MINITEST做到這一點:

def setup 
    @view_flow = ActionView::OutputFlow.new 
end 

test 'when page_title is set' do 
    @view_flow.set(:page_title, "Hello") 
    expected_html = '<title>Hello | My Amazing Website</title>' 
    assert_equal expected_html, title 
end