Skip to content

Commit

Permalink
Improve errors method check in be_valid matcher (#2096)
Browse files Browse the repository at this point in the history
If the `.be_valid?` matcher fails, it checks for the presence of a `.errors` method and uses it, if present, in the failure message.  This works great, unless the subject happens to include an `errors` method that takes an argument, in which case we get an error (because we call
errors with 0 arguments), this checks the arity of that method before we call it.
  • Loading branch information
kkuchta authored and JonRowe committed Mar 12, 2019
1 parent edcd8e1 commit 6ad4943
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/rspec/rails/matchers/be_valid.rb
Expand Up @@ -15,7 +15,7 @@ def matches?(actual)
def failure_message
message = "expected #{actual.inspect} to be valid"

if actual.respond_to?(:errors)
if actual.respond_to?(:errors) && actual.method(:errors).arity < 1
errors = if actual.errors.respond_to?(:full_messages)
actual.errors.full_messages
else
Expand Down
16 changes: 16 additions & 0 deletions spec/rspec/rails/matchers/be_valid_spec.rb
Expand Up @@ -24,9 +24,19 @@ def valid?
end
end

class Car
def valid?
false
end

def errors(_)
end
end

let(:post) { Post.new }
let(:book) { Book.new }
let(:boat) { Boat.new }
let(:car) { Car.new }

it "includes the error messages in the failure message" do
expect {
Expand All @@ -46,6 +56,12 @@ def valid?
}.to raise_exception(/expected .+ to be valid\z/)
end

it "includes a brief error message when error message is wrong arity" do
expect {
expect(car).to be_valid
}.to raise_exception(/expected .+ to be valid\z/)
end

it "includes a failure message for the negative case" do
allow(post).to receive(:valid?) { true }
expect {
Expand Down

0 comments on commit 6ad4943

Please sign in to comment.