Question

I am reading through the RoR guide on testing (http://guides.rubyonrails.org/testing.html)

About 1/5th down the page it says ""To see how a test failure is reported, you can add a failing test to the post_test.rb test case."

test "should not save post without title" do
  post = Post.new
  assert !post.save
end

I am trying to understand what the use of the bang (!) before post save means.

In an app that I am developing I have a validattion in the model for post

validates :post, presence: true
  • If I leave the line as it is, the test passes.
  • If I remove the bang the test fails (because of the validation)
  • If I move the bang to after the save an exception is raised (because the validation fails and the bang returns the error message, I think)

So can you help me understand please, what does the bang in front do nd why does it make the test pass?

Question edit / extension: Why is the second test a fail (F) and not an exception (E)

Was it helpful?

Solution

The bang (!) inverts the result of post.save

assert post.save reads assert that the post does save

assert !post.save reads assert that the post doesn't save

Check out the Ruby Logical Operators section at http://www.tutorialspoint.com/ruby/ruby_operators.htm

Edit for extended question:

assert looks for a true result. If the result is true, it returns a pass for that test. If the result is not true, it returns a fail for that test.

Some pseudo code for the asset method,

def assert(result)
  if result == true
    return 'Pass'
  else
    return 'Fail'
  end
end

assert true

=> 'Pass'

assert false

=> 'Fail'

If there is an exception in the test or code, the test method will rescue the exception and return (E).

Some pseudo code for the test method,

def test(description, &block)
  begin
    yield
  rescue
    return 'Exception'
  end
end

test 'test description' do
  raise 'An error occurred'
end

=> 'Exception'

OTHER TIPS

! is the Logical Not prefix operator - it is not related to variables or methods.

It can be summarized as:

x            !x
---------    ---------
nil          true
false        true
true         false
<other>      false

(In this case x is the result of evaluating post.save.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top