这是attr_accessible引起的吗?

发布于 2024-11-01 18:32:09 字数 778 浏览 3 评论 0原文

我最近刚刚使用 attr_accessible 字段更新了我的模型,突然有些测试无法正常工作,正如我所期望的那样。但是,我有一个规范,例如:

context "when user buys a game item" do
  let(:inventory) {@user.inventory << Factory(:inventory)}

  it "should present an error if the id ..." do
    GameItem.stub(:find_by_id).and_return(Factory(:game_item))
    @user.inventory.should == 1  # TEST
    post :buy, :id => (game_item.id + 1)
    flash[:error].should == I18n.t('error.invalid_post')
    response.should redirect_to melee_url('Weapon')
  end
end

@user.inventory.should == 1 行只是我现在所做的检查。由于某种原因,库存nil。发生这种情况是因为 << 操作吗?由于用户模型的 inventory_id 属性,我猜这是最有可能的。

我不得不说,attr_accessible 通常对我来说似乎是一种 hack,我有点不喜欢它,尽管我知道为什么应该使用它。您认为是这样吗?如果是这样,我怎样才能避开那张支票?

I just lately update my model with attr_accessible fields and suddenly some tests would not work, as i would expect. However, i have a spec like:

context "when user buys a game item" do
  let(:inventory) {@user.inventory << Factory(:inventory)}

  it "should present an error if the id ..." do
    GameItem.stub(:find_by_id).and_return(Factory(:game_item))
    @user.inventory.should == 1  # TEST
    post :buy, :id => (game_item.id + 1)
    flash[:error].should == I18n.t('error.invalid_post')
    response.should redirect_to melee_url('Weapon')
  end
end

The line @user.inventory.should == 1 is just a check that i made now. The inventory is nil for some reason. Does this happen because of the << operation? I would guess that this is most probable, due to the inventory_id attribute of the User model.

I have to say that attr_accessible generally seems like a hack to me and i kinda don't like it, though i can see why it should be used. Do you think this is the case? If so, how can i stay clear of that check?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一抹微笑 2024-11-08 18:32:09

let 是懒惰的;除非使用您定义的变量,否则它不会调用该块,并且我看不到您在任何地方访问 inventory 。您访问 @user.inventory,但这不是同一件事。

要么丢失 let 定义并将其放入您的 it 块中,或者确保在确保它执行预期操作之前先调用它。

let is lazy; it won't call the block unless the variable you're defining is used, and I don't see you accessing inventory anywhere. You access @user.inventory, but that's not the same thing.

Either lose the let definition and just put it in your it block, or make sure you call it first before you make sure it did what it was supposed to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文