我测试了这个部分:
<% if user_signed_in? %>
<%= menu_item "Logout", destroy_user_session_path %>
<% else %>
<%= menu_item "Login",new_user_session_path %>
<% end %>
这是我的测试:
require 'spec_helper'
describe "layouts/_header.html.erb" do
before do
view.stub(:user_signed_in?).and_return(true)
end
it "should have the right links on the header" do
render
rendered.should have_link('Login', new_user_session_path)
rendered.should have_link('Logout', destroy_user_session_path)
end
end
使用此方法,我只测试一个if
分支,即真正的分支。
如何测试所有if
分支?
答案 0 :(得分:1)
使用上下文块为存根提供范围:
require 'spec_helper'
describe "layouts/_header.html.erb" do
context "logged" do
before do
view.stub(:user_signed_in?).and_return(true)
end
it "should have the right links on the header" do
render
rendered.should have_link('Login', new_user_session_path)
end
end
context "not logged" do
before do
view.stub(:user_signed_in?).and_return(false)
end
it "should have logout button" do
render
rendered.should have_link('Logout', destroy_user_session_path)
end
end
end