Skip to content

Commit c6da310

Browse files
BritniBritni
authored andcommitted
Allow use of composable matchers inside be_a_new#with
1 parent 0e2daab commit c6da310

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

lib/rspec/rails/matchers/be_a_new.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def attributes
4949

5050
def attributes_match?(actual)
5151
attributes.stringify_keys.all? do |key, value|
52-
actual.attributes[key].eql?(value)
52+
actual.attributes[key].eql?(value) || (value.respond_to?(:expected, true) && actual.attributes[key].include?(value.expected))
5353
end
5454
end
5555

spec/rspec/rails/matchers/be_a_new_spec.rb

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,61 @@ def new_record?; true; end
6565
end
6666
end
6767

68+
context "with composable matchers" do
69+
context "one attribute is a composable matcher" do
70+
it "passes" do
71+
expect(record).to be_a_new(record.class).with(
72+
:foo => a_string_matching("foo"))
73+
end
74+
75+
it "fails" do
76+
expect {
77+
expect(record).to be_a_new(record.class).with(
78+
:foo => a_string_matching("bar"))
79+
}.to raise_error{|e|
80+
expect(e.message).to match(/attribute \{.*\} was not set on #{Regexp.escape record.inspect}/)
81+
expect(e.message).to match(/@expected="bar"/)
82+
}
83+
end
84+
context "matcher is wrong type" do
85+
it "fails" do
86+
expect {
87+
expect(record).to be_a_new(record.class).with(
88+
:foo => a_hash_including({:no_foo => "foo"}))
89+
}.to raise_error {|e|
90+
expect(e.message).to eq("no implicit conversion of Hash into String").or eq("can't convert Hash into String")
91+
}
92+
end
93+
end
94+
end
95+
96+
context "two attributes are composable matchers" do
97+
context "both matchers present in actual" do
98+
it "passes" do
99+
expect(record).to be_a_new(record.class).with(
100+
:foo => a_string_matching("foo"),
101+
:bar => a_string_matching("bar")
102+
)
103+
end
104+
end
105+
106+
context "only one matcher present in actual" do
107+
it "fails" do
108+
expect {
109+
expect(record).to be_a_new(record.class).with(
110+
:foo => a_string_matching("foo"),
111+
:bar => a_string_matching("barn")
112+
)
113+
}.to raise_error {|e|
114+
expect(e.message).to match(/attributes \{.*\} were not set on #{Regexp.escape record.inspect}/)
115+
expect(e.message).to match(/@expected="foo"/)
116+
expect(e.message).to match(/@expected="barn"/)
117+
}
118+
end
119+
end
120+
end
121+
end
122+
68123
context "no attributes same" do
69124
it "fails" do
70125
expect {

0 commit comments

Comments
 (0)