bia*_*idp 6 ruby unit-testing rspec ruby-on-rails
我有一个看起来像这样的课:
class Foo < ActiveRecrod::Base
has_many :bars
def nasty_bars_present?
bars.where(bar_type: "Nasty").any?
end
validate :validate_nasty_bars
def validate_nasty_bars
if nasty_bars_present?
errors.add(:base, :nasty_bars_present)
end
end
end
Run Code Online (Sandbox Code Playgroud)
在测试#nasty_bars_present?我的方法就是写一个rspec测试来存根吧关联但允许自然执行的地方.就像是:
describe "#nasty_bars_present?" do
context "with nasty bars" do
before { foo.stub(:bars).and_return([mock(Bar, bar_type: "Nasty")]) }
it "should return true" do
expect(foo.nasty_bars_present?).to be_true
end
end
end
Run Code Online (Sandbox Code Playgroud)
上面的测试给出了关于没有数组方法的错误.如何包装模拟以便在哪里执行适当的?
谢谢!
小智 5
对于RSpec 2.14.1(它也适用于RSpec 3.1),我会尝试这样做:
describe "#nasty_bars_present?" do
context "with nasty bars" do
before :each do
foo = Foo.new
bar = double("Bar")
allow(bar).to receive(:where).with({bar_type: "Nasty"}).and_return([double("Bar", bar_type: "Nasty")])
allow(foo).to receive(:bars).and_return(bar)
end
it "should return true" do
expect(foo.nasty_bars_present?).to be_true
end
end
end
Run Code Online (Sandbox Code Playgroud)
这样,如果你bars.where(bar_type: "Nasty")
在where语句中没有特定条件的情况下调用,你就不会得到条形图bar_type: "Nasty"
.它可以重复用于将来模拟条形图(至少对于返回单个实例,对于多个实例,您将添加另一个实例).
归档时间: |
|
查看次数: |
11284 次 |
最近记录: |