Rspec partials problem
I am writing specs for View, that has a menu (which is in a partial) rendered in layout. I want to write specs for selected menu. Here is the code
it "should have User Administration link" do
template.stub!(:render).and_return(:partial => "layouts开发者_C百科/admin/menu")
do_render
#render :partial => "layouts/admin/menu" #do
response.should have_tag('div.menu1')
response.should have_tag('ul') do
response.should have_tag('li')do
with_tag("a[href=?]", admin_users_path)
end
end
end
This spec is failing. I am not getting right way to write specs for partials, I have tried with:
template.should_receive(:render).with(:partial => "/layout/admin/menu")
too.
Thanks and regards, Pravin.
I don't think this line:
template.stub!(:render).and_return(:partial => "layouts/admin/menu")
is doing what you think it's doing. RSpec is not going to call template.render :partial => "layouts/admin/menu". It's just going to stub out render and return {:partial => "layouts/admin/menu"} when render is called.
Why stub render at all? You want the view to actually render so the response body has that data you want to test, unless I'm missing something, which I may be. : )
I realize this is an old discussion, but I came across it while having the a similar problem, so maybe my solution will help someone else.
My problem was I was my mocked method wasn't being called because I didn't get the "with" right. Here's what I had, which wasn't working:
# widgets/new.html.erb
<% form_for(@widgets) do |f| %>
<%= render :partial => "form", :locals => {:f => f} %>
<%= f.submit "Create" %>
<% end %>
# widgets/new.html.erb_spec.rb
describe "widgets/new.html.erb" do
let(:widget) { @widget ||= Widget.new }
it "displays a form" do
template.should_receive(:render).
with(:partial => "form").
and_return("<span id=\"rendered-form\"/>")
render
response.should have_tag("form[method=?][action=?]", "put", widget_path(widget)) do |form|
form.should have_tag("span[id=?]", "rendered-form")
form.should have_tag("input[type=?][value=?]", "submit", "Create")
end
end
end
Of course it's obvious now why it wasn't working, I was calling:
render :partial => "form", :locals => {:f => f}
But my spec was mocking:
render :partial => "form"
So naturally, my mocked method wouldn't be called. Once I realized that, I started trying to mock form_for, and all kinds of other things, but the solution was much easier:
template.should_receive(:render).
with(hash_including(:partial => "form")).
and_return("<span id=\"rendered-form\"/>")
hash_including() was what was missing.
So maybe your problem is similar: you're not really mocking what you think you're mocking.
精彩评论