开发者

Factory Girl after_build callback and overrides issue in rspec

开发者 https://www.devze.com 2023-03-22 23:28 出处:网络
We\'re having a problem with Factory Girl\'s new after_build callback and getting the override parameters to work.we\'ve defined a model as:

We're having a problem with Factory Girl's new after_build callback and getting the override parameters to work. we've defined a model as:

factory :widget do
  name "Widget Name"
  position 1
  creator
  content_type "text_content"
  content "This is the content"
  change_comment "This is the change comment"
  after_build do |widget|
    widget.page = Factory.create(:page)
    widget.canvas = widget.page.canvas
  end
end

note that a page and a widget in this example both require a canvas; a widget can optionally have a page. we want the factory to build the widget belonging to a page, and both the widget and page belong to the same canvas.

we have an rspec test that needs to test that not having valid canvas makes the widget model invalid

context "Canvas" do
    it "should be required" do
        widget = Factory.build(:widget, :canvas => nil)
        widget.should_not be_valid
    end
end

i.e. Factory.build(:widget, :canvas => nil) should not be valid as the canvas is being passed in nil, however the after_build method is ignoring this and still applying a canvas to the model.

Note: we can work-ar开发者_Python百科ound this issue by changing the rspec test to the following, where we create a valid model then set the canvas to nil as a 2nd step and this does work correctly i.e.

context "Canvas" do
    it "should be required" do
        widget = Factory.build(:widget)
        widget.canvas = nil
        widget.should_not be_valid
    end
end

however this feels like we've lost some of the core functionality of Factory Girl, so we're hopeful we're missing something in our factory girl model set up that will let us accomplish this more correctly. Greatly appreciate any insights people can provide!


I don't think I can comment on the question, so I will post a fix to a slightly-different issue with your code here.

I think your widget factory will always create a new page/canvas, even if you pass a non-nil page/canvas into Factory.build/Factory.create. Here's a solution for that, except for the nil/false cases:

after_build do |widget|
  widget.page   ||= Factory.create(:page)
  widget.canvas ||= widget.page.canvas
end

I'm still looking for a solution for the falsey cases...

0

精彩评论

暂无评论...
验证码 换一张
取 消