1

我正在我的组模型上测试一种方法。它依赖于通过工厂创建一些徽章类型。

这是代码

it "add itself to badges with method add_to_badgetypes" do
    badge = FactoryGirl.create(:badgetype)
    old_badge_ids = badge.group_ids.split(",")
    badge2 = FactoryGirl.create(:badgetype, :group_ids => "3,4,5")
    group.add_to_badgetypes(badge.id, badge2.id)
    expect( badge.group_ids ).to eq( old_badge_ids.push(group.id).join(",") ) 
end

'

badge.group_ids' 之前是“200, 300”,之后应该是“200,300,#{group.id}”。当我跟踪日志时,我看到了这个:

  `   Badgetype Load (0.5ms)  SELECT group_ids FROM `badge_types` WHERE `badge_types`.`id` = 40 LIMIT 1

   (0.2ms)  SAVEPOINT active_record_1

   (0.3ms)  UPDATE `badge_types` SET `group_ids` = '200,300,15' WHERE `badge_types`.`id` IS NULL

   (0.2ms)  RELEASE SAVEPOINT active_record_1

  Badgetype Load (0.4ms)  SELECT group_ids FROM `badge_types` WHERE `badge_types`.`id` = 41 LIMIT 1

   (0.1ms)  SAVEPOINT active_record_1

   (0.3ms)  UPDATE `badge_types` SET `group_ids` = '3,4,5,15' WHERE `badge_types`.`id` IS NULL

   (0.1ms)  RELEASE SAVEPOINT active_record_1

   (0.3ms)  ROLLBACK

   (0.1ms)  BEGIN

`

所以它成功更新了 group_ids,但由于某种原因测试失败,如果我 pp badge.group_ids 我得到原始值(200,300),而不是更新后的值。

我认为这与“SAVEAPOINT active_record_1”有关,然后是 UPDATE,然后是 RELEASE SAVEPOINT。如果是这样,为什么?

我怎样才能让这个规范通过,因为它似乎都在数据库中搞砸了,而不是方法。

谢谢

编辑

通过在控制台中玩耍发现了一些更有趣的信息。如果我创建一个工厂并为其分配一行:

g = FactoryGirl.create(:group)

然后运行:

g.add_to_badgetype(1,2)

我得到这个 SQL

1.9.3-p286 :080 > g.add_to_badgetypes(1, 2)
  Badgetype Load (0.5ms)  SELECT group_ids FROM `badge_types` WHERE `badge_types`.`id` = 1 LIMIT 1
   (0.1ms)  BEGIN
   (0.2ms)  UPDATE `badge_types` SET `group_ids` = 'test,8,9,10' WHERE `badge_types`.`id` IS NULL
   (0.1ms)  COMMIT
  Badgetype Load (0.3ms)  SELECT group_ids FROM `badge_types` WHERE `badge_types`.`id` = 2 LIMIT 1
   (0.1ms)  BEGIN
   (0.2ms)  UPDATE `badge_types` SET `group_ids` = '200,300,8,9,10' WHERE `badge_types`.`id` IS NULL
   (0.1ms)  COMMIT
 => [1, 2] 

注意奇怪的 UPDATE 语句“WHERE badge_types.id IS NULL”

如果在创建工厂之后,我将它重新分配给一个变量,然后运行相同的命令,它可以找到:

1.9.3-p286 :081 > g = Group.last
  Group Load (0.5ms)  SELECT `groups`.* FROM `groups` ORDER BY `groups`.`id` DESC LIMIT 1
 => #<Group id: 10, group_name: "Test Group", short_name: "test_group", enrollment: false, kiosk: false, landing: 0, ro_landing: 0> 
1.9.3-p286 :082 > g.add_to_badgetypes(1, 2)
  Badgetype Load (0.6ms)  SELECT `badge_types`.* FROM `badge_types` WHERE `badge_types`.`id` = 1 LIMIT 1
   (0.1ms)  BEGIN
   (0.4ms)  UPDATE `badge_types` SET `group_ids` = 'test,8,9,10' WHERE `badge_types`.`id` = 1
   (0.2ms)  COMMIT
  Badgetype Load (0.4ms)  SELECT `badge_types`.* FROM `badge_types` WHERE `badge_types`.`id` = 2 LIMIT 1
   (0.1ms)  BEGIN
   (0.4ms)  UPDATE `badge_types` SET `group_ids` = '200,300,8,9,10' WHERE `badge_types`.`id` = 2
   (0.2ms)  COMMIT
 => [1, 2] 

显然,作为工厂的组导致 SQL 更新语句查找 NULL 的 id。

有任何想法吗?

4

1 回答 1

2

啊啊啊,我想通了。

我只需要重新加载变量“badgetype”

在平等测试之前,我添加了

@badge.reload

等等。奇怪的。

于 2013-01-30T08:29:52.077 回答