Search code examples
ruby-on-railsintegration-testingshoulda

how can I structure this rails integration test (with shoulda) so that "visit" is not called each time?


Using Test::Unit and shoulda, I wanted to write a test that has expectations that are clear and so I came up with this:

context "logged in as seller" do
  setup do
    login @seller
    visit offer_path(@seller_offer)
  end

  should "not see feedback" do
    assert has_no_selector?("#feedback")
  end

  should "see 'cancel offer' button" do
    assert has_selector?("#cancel_offer_button")        
  end

  should "see 'comment' button" do
    assert has_selector?("#comment_button")
  end

  should "not see 'accept offer' button" do
    assert has_no_selector?("#accept")
  end

end

The problem is, before each "should" block, the setup is re-executed-- meaning a two page requests (one for the login helper, and the other for the call to "visit").

I tried doing

context "logged in as seller" do
  login @seller
  visit offer_path(@seller_offer)

  should ...

But that does not seem to work... Obviously I could do:

context "logged in as seller" do
  should "have desired results" do
    login @seller
    visit offer_path(@seller_offer)

    # should see 'cancel offer' button
    assert has_selector?("#cancel_offer_button")        

    # should see 'comment' button"
    assert has_selector?("#comment_button")

    etc..

But that's not exactly what I am looking for.

-patrick


Solution

  • For starters: if you want your tests to test only one thing, as it is supposed to be, there is no solution to this problem, and you are already doing the right thing.

    However, there are alternative approaches: instead of doing the full integration test, and testing the view (the appearance of each element on the page) in the integration test, I generally do the following:

    • test the controller, without the views, preferably without hitting the database (using stubs).
    • test the views in isolation: there I test that everything is rendered correctly
    • in the integration tests:
      • use cucumber
      • do a happy-path click-thru approach (errors and such have been tested separately)
      • focus on the javascript parts

    Hope this helps.