Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions lib/contracts/attrs.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
module Contracts
module Attrs
def attr_reader_with_contract(*names, contract)
Contract Contracts::None => contract
attr_reader(*names)
names.each do |name|
Contract Contracts::None => contract
attr_reader(name)
end
end

def attr_writer_with_contract(*names, contract)
Contract contract => contract
attr_writer(*names)
names.each do |name|
Contract contract => contract
attr_writer(name)
end
end

def attr_accessor_with_contract(*names, contract)
Expand Down
50 changes: 47 additions & 3 deletions spec/attrs_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ def initialize(name)
@name_r = name
@name_w = name
@name_rw = name

@name_r_2 = name
@name_w_2 = name
@name_rw_2 = name
end

attr_reader_with_contract :name_r, String
attr_writer_with_contract :name_w, String
attr_accessor_with_contract :name_rw, String
attr_reader_with_contract :name_r, :name_r_2, String
attr_writer_with_contract :name_w, :name_w_2, String
attr_accessor_with_contract :name_rw, :name_rw_2, String
end

context "attr_reader_with_contract" do
Expand All @@ -27,6 +31,16 @@ def initialize(name)
.to(raise_error(ReturnContractError))
end

it "getting valid type for second val" do
expect(Person.new("bob").name_r_2)
.to(eq("bob"))
end

it "getting invalid type for second val" do
expect { Person.new(1.3).name_r_2 }
.to(raise_error(ReturnContractError))
end

it "setting" do
expect { Person.new("bob").name_r = "alice" }
.to(raise_error(NoMethodError))
Expand All @@ -48,6 +62,16 @@ def initialize(name)
expect { Person.new("bob").name_w = 1.2 }
.to(raise_error(ParamContractError))
end

it "setting valid type for second val" do
expect(Person.new("bob").name_w_2 = "alice")
.to(eq("alice"))
end

it "setting invalid type for second val" do
expect { Person.new("bob").name_w_2 = 1.2 }
.to(raise_error(ParamContractError))
end
end

context "attr_accessor_with_contract" do
Expand All @@ -70,6 +94,26 @@ def initialize(name)
expect { Person.new("bob").name_rw = 1.2 }
.to(raise_error(ParamContractError))
end

it "getting valid type for second val" do
expect(Person.new("bob").name_rw_2)
.to(eq("bob"))
end

it "getting invalid type for second val" do
expect { Person.new(1.2).name_rw_2 }
.to(raise_error(ReturnContractError))
end

it "setting valid type for second val" do
expect(Person.new("bob").name_rw_2 = "alice")
.to(eq("alice"))
end

it "setting invalid type for second val" do
expect { Person.new("bob").name_rw_2 = 1.2 }
.to(raise_error(ParamContractError))
end
end
end
end