On 19 Feb 2009, at 21:53, Zach Dennis wrote:

On Thu, Feb 19, 2009 at 4:24 PM, Matt Wynne <m...@mattwynne.net> wrote:

On 19 Feb 2009, at 20:54, Martin wrote:

Hi,

I'm trying to test my views using rspec. I want to test my edit- and
new-view also for the case an error occurs (something like "title can't be
blank" and so on).
Can someone point me please to an example where I can see how to mock my
model and stub all methods needed for the view?

I guess this isn't exactly what you want to hear, but I would counsel you against mocking your whole model object for a form with lots of fields - those kind of 'broad' mocks can be very brittle to changes in your domain
model.

Can you try using stub_model instead? This creates an instance of your actual model class, but with a crippled database connection. You can then create an invalid model object and throw it to the view. Something like:

assigns[:book] = stub_model(Book, :title => '')

If your model is at all interesting, you might want to keep the attributes
that make a valid Book somewhere:

valid_book = {
:title => "Test Book Title",
:author => "Test Author"
}
assigns[:book] = stub_model(Book, valid_book.merge(:title => ''))

I generally hide these behind a helper method, like

def stub_book(attributes = {})
stub_model Book, {
  :title => "Test Book Title",
  :author => "Test Author"
}.merge(attributes)
end

Why hide them behind a helper? Why not just only specify them in
examples where they are used? ie:

it "should display the book title" do
  @book.stub!(:title).and_return "The Scarlet Letter"
  render ...
  response.should include_text("The Scarlet Letter")
end

Why hide them in a helper? because I don't want the noise of all the attributes needed to make a valid book in each test.

@book = stub_book :title => "The Scarlet Letter"

This is basically the same pattern people use things like factory_girl for, just using stub_model.


Matt Wynne
http://blog.mattwynne.net
http://www.songkick.com

_______________________________________________
rspec-users mailing list
rspec-users@rubyforge.org
http://rubyforge.org/mailman/listinfo/rspec-users

Reply via email to