The new programmer is here. I am a student working on my project, which is a Reddit clone. I am currently familiar with RSPEC. I should start writing my own model tests, which will be used in further exercises. The model in question is not being created; it will be in the next assignment. Can someone please check if I did this correctly?
At the next checkpoint, we will add a voting model. This model has an inclusion check function. Enabling validation ensures that the voice value attribute is 1 or -1. If a vote is started with any other value, it will not be saved.
specifications / models / vote_spec.rb
describe Vote do describe "validations" do describe "value validation" do it "only allows -1 or 1 as values" do
Write a specification that claims that checks work properly.
Use RSpec expect () for eq () syntax. As you recall from the specifications in Ruby exercises, you can argue that something must be equal to false or true.
You wonβt be able to run tests because we donβt have a model created that we are testing.
Below is my implementation:
describe Vote do describe "validations" do before do 2.times { @vote.create(value: 1) } 3.times { @vote.create(value: -1) } 2.times { @vote.create(value: 3) } end describe "value validation" do it "only allows -1 or 1 as values" do expect ( @vote.value ).to eq(-1) end it "only allows -1 or 1 as values" do expect ( @vote.value ).to eq(1) end end end end
Sincerely.
Editing: here is a revision:
describe Vote do describe "validations" do before do 2.times { Vote.create(value: 1) } 3.times { Vote.create(value: 0) } 2.times { Vote.create(value: 3) } end describe "value validation" do it "only allows -1 as value" do expect ( @vote.value ).to eq(-1) end it "only allows 1 as value" do expect ( @vote.value ).to eq(1) end it "it prohibits other values" do expect( @vote.value ).to_not be_valid end end end end
I also tried with this code, which worked first, but now fails in the following assignment:
require 'rails_helper' describe Vote do describe "value validation" do it "allows -1" do value = Vote.create(value: -1) expect(value).to be_valid end it "allows +1" do value = Vote.create(value: +1) expect(value).to be_valid end it "prohibits other values" do value = Vote.create(value: 0) expect(value).to_not be_valid end end end βΆ rspec spec ...FFF Failures: 1) Vote value validation allows -1 Failure/Error: value = Vote.create(value: -1) NoMethodError: undefined method `update_rank' for nil:NilClass # ./app/models/vote.rb:12:in `update_post' # ./spec/models/vote_spec.rb:7:in `block (3 levels) in <top (required)>' 2) Vote value validation allows +1 Failure/Error: value = Vote.create(value: +1) NoMethodError: undefined method `update_rank' for nil:NilClass # ./app/models/vote.rb:12:in `update_post' # ./spec/models/vote_spec.rb:12:in `block (3 levels) in <top (required)>' 3) Vote value validation prohibits other values Failure/Error: expect(value).to eq(false) expected: false got: