这是attr_accessible引起的吗?
我最近刚刚使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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 accessinginventory
anywhere. You access@user.inventory
, but that's not the same thing.Either lose the
let
definition and just put it in yourit
block, or make sure you call it first before you make sure it did what it was supposed to.