我正在尝试为vote_spec模型编写规范代码。不知道究竟是什么我做错了。我认为它可能是在前一个块中的第一个@vote属性。
验证应该如何运作:
Console
v = Vote.new(value: 1)
v.valid? #=> true
v2 = Vote.new(value: -1)
v2.valid? #=> true
v3 = Vote.new(value: 2)
v3.valid? #=> false
这是错误:
Failure/Error: @vote = Vote.create(:post_id)
ArgumentError:
When assigning attributes, you must pass a hash as an argument.
这是我的vote_spec.rb
require 'rails_helper'
describe Vote do
describe "validations" do
before do
@vote = Vote.create(:post_id)
@vote.create(value: 1)
@vote.create(value: -1)
end
describe "first_validation" do
it "only allows -1 as a value" do
expect(@vote.first_validation).to eq(-1)
end
end
describe "second_validation" do
it "only allows 1 as a value" do
expect(@vote.second_validation).to eq(1)
end
end
end
端
答案 0 :(得分:4)
如果你想测试验证,也许你可以这样做:
describe "validations" do
it 'is valid if the value is 1' do
expect(Vote.new(value: 1)).to be_valid
end
it 'is valid if the value is -1' do
expect(Vote.new(value: -1)).to be_valid
end
[-3, 0, 4].each do |invalid_value|
it "is not valid if the value is #{invalid_value}" do
expect(Vote.new(value: invalid_value)).not_to be_valid
end
end
end
答案 1 :(得分:0)
Amanjot,
正如Sasha在评论中提到的那样。您可以继续使用以下代码我认为
require 'rails_helper'
describe Vote do
describe "validations" do
before do
@first_vote = Vote.create(value: -1) # Vote.new(value: -1) - should try this too
@second_vote= Vote.create(value: 1) # Vote.new(value: 1) - should try this too
end
describe "first_validation" do
it "only allows -1 as a value" do
expect(@first_vote.value).to eq(-1)
end
end
describe "second_validation" do
it "only allows 1 as a value" do
expect(@second_vote.value).to eq(1)
end
end
end
尝试这样的事情。您需要在投票模型上使用create
操作。