gpt4 book ai didi

ruby-on-rails - rails rspec 在测试时访问其他表

转载 作者:太空宇宙 更新时间:2023-11-03 16:33:06 24 4
gpt4 key购买 nike

我是 Rails 的新手,发现自己在理解数据库表之间的关系时遇到了一些问题(我猜?)。

我的问题如下:

我有一个 Users 表,其中包含有关用户的信息,包括他们的电子邮件地址和另一个包含“游戏”的表,我想管理那些玩过的玩家。当玩家想要提交他们的游戏时,他们必须通过他们的电子邮件地址指定参与游戏的用户。我想验证这些玩家是否真的存在。

我的游戏模型:

class Game < ActiveRecord::Base
attr_accessible :caster1, :caster2, :faction1, :faction2, :player1, :player2, :points, :won

before_save { |game| player1 = player1.downcase }
before_save { |game| player2 = player2.downcase }

validate :existence_of_both_players

...
(some more validations)
...

private
def existence_of_both_players
User.exists?(:email => :player1.downcase) && User.exists?(:email => :player2.downcase)
end
end

我的测试用例如下:

require 'spec_helper'

describe Game do

before do
@game = Game.new( player1: "foobar@example.com",
faction1: "Some faction",
caster1: "Some caster",
player2: "bazbaz@example.com",
faction2: "Some other faction",
caster2: "Some other caster",
points: 35,
won: true)
end

...
(some other specs)
...

describe "saving a game" do
let(:player1) { User.create(name: "Example1",
email: "example1@foo.bar",
password: "foobar",
password_confirmation: "foobar") }
let(:player2) { User.create(name: "Example2",
email: "example2@foo.bar",
password: "foobar",
password_confirmation: "foobar") }

describe "with invalid players" do

describe "when both players do not exist" do
before { @game.player1 = @game.player2 = "some_wrong_user@example.com" }
it { should_not be_valid }
end

describe "when player1 does not exist" do
before { @game.player2 = player2 }
it { should_not be_valid }
end

describe "when player2 does not exist" do
before { @game.player1 = player1 }
it { should_not be_valid }
end
end

describe "with valid players" do
before do
@game.player1 = player1
@game.player2 = player2
end

it { should be_valid }
end
end
end

(抱歉代码太多,我只是觉得它会有所帮助)。

我的测试失败了,我很确定原因很明显,遗憾的是对我来说不是。

Failures:

1) Game saving a game with invalid players when both players do not exist
Failure/Error: it { should_not be_valid }
expected valid? to return false, got true
# ./spec/models/game_spec.rb:108:in `block (5 levels) in <top (required)>'
...

我真的想不通,为什么这行不通。我阅读了 Rails 书籍并观看了几个截屏视频,但没有一个能正确解释我的问题。

由于这是我在 stackoverflow 上的第一篇文章,如果这篇文章过于冗长,请告诉我。提前致谢。

最佳答案

自定义验证器方法应该调用 errors.add 来发出错误信号。所以在你的情况下是这样的:

    def existence_of_both_players
player_one_exists = User.find_by_email :player1.downcase
player_two_exists = User.find_by_email :player2.downcase
unless player_one_exists and player_two_exists
errors.add :game, "both players need to exist"
end
end

阅读更多关于 ActiveRecord Validations and Callbacks 的指南.

关于ruby-on-rails - rails rspec 在测试时访问其他表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12511407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com