Skip to content

Instantly share code, notes, and snippets.

@damonjmurray
Created February 10, 2016 02:53
Show Gist options
  • Save damonjmurray/d1a289d96dd4ee45d116 to your computer and use it in GitHub Desktop.
Save damonjmurray/d1a289d96dd4ee45d116 to your computer and use it in GitHub Desktop.
RSpec subject behaviour question
require 'spec_helper'
class Foo
def self.bar(first, second, third)
err_msg = '%s cannot be nil'
raise ArgumentError, err_msg % 'first' unless first
raise ArgumentError, err_msg % 'second' unless second
raise ArgumentError, err_msg % 'third' unless third
"#{first} #{second} #{third}"
end
end
describe Foo do
[
{ first: nil, second: 2, third: 3 },
{ first: 1, second: nil, third: 3 },
{ first: 1, second: 2, third: nil }
].each_with_index do |args_hash, index|
subject { Foo.bar(*args_hash.values) }
it "raises an ArgumentError when #{args_hash.keys[index]} is nil" do
expected_err_msg = "#{args_hash.keys[index]} cannot be nil"
# this works:
expect { Foo.bar(*args_hash.values) }.to raise_error(ArgumentError, expected_err_msg) }
# this does not:
# Using subject in this way appears to keep sending through the last set of args
# each time it is called
#expect { subject }.to raise_error(ArgumentError, expected_err_msg)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment